malloc函数
概要:
#include <stdlib.h>
void *malloc(size_t size);
描述:
该函数给对象分配指定大小的内存,其大小由参数size指定,内存表示是不确定的。
分配内存的生存期从内存分配开始到内存释放结束。如果内存被成功分配,函数返回指向分配内存开始位置(即最低字节地址。)的指针。如果内存不能被分配,函数返回空指针。
如果请求的内存大小为0,函数行为将由实现定义:函数可能返回空指针表示错误;函数也可能像非0值一样返回指针,但返回的指针不能用于访问对象。
调用free函数或者realloc函数将释放全部或者部分分配内存。
参数:
size_t size
指定分配内存的大小。
返回值:
如果调用成功,函数返回指向分配内存的指针;如果失败,函数返回空指针。
范例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
/*函数malloc范例*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/*统计一支球队一个赛季的进球数。*/
int match; //比赛场数。
int total = 0; //总进球数。
int *pGoal; //单场比赛的进球数。
puts("Input the total number of matches.");
if(((scanf("%d", &match)) != 1) || (match <= 0))
{
puts("Invalid input.");
return EXIT_FAILURE;
}
/*分配内存。*/
pGoal = malloc(match*sizeof(int));
if(pGoal==NULL)
{
puts("Memory allocation failed.");
return EXIT_FAILURE;
}
/*统计数据。*/
for(int i=0; i<match; ++i)
{
printf("Match %d: ", (i+1));
if(((scanf("%d", &pGoal[i])) != 1) || (pGoal[i] < 0))
{
puts("Invalid input.");
free(pGoal);
return EXIT_FAILURE;
}
total += pGoal[i];
}
/*释放内存。*/
free(pGoal);
printf("Total goals: %d\n", total);
return 0;
}
|
结果:
假设输入为:
Input the total number of matches.
3
Match 1: 2
Match 2: 1
Match 3: 3
将输出:
Total goals: 6
相关内容:
主要参考资料:
1、ISO/IEC 9899:2024
2、ISO/IEC 9899:2018