malloc
与calloc
都可以用来申请内存空间,从log上看,两个申请的都是一片连续的空间。只是malloc
申请的空间里面的值是不确定,而calloc
申请的内存空间会赋初值为默认值。
#include <stdio.h>
#include <stdlib.h>
// malloc & calloc 区别
int main(void)
{
const int LEN = 7;
int * p_nums;
p_nums = malloc(LEN * sizeof(int));
*(p_nums +3) = 11;
printf("malloc 申请到的空间使用:\n");
for(int i=0; i<LEN; i++)
{
printf("%p , %d \n",(p_nums+i),*(p_nums+i));
}
printf("malloc last - start = %d\n",(p_nums+LEN -1 - p_nums));
int * p_arr = calloc(LEN,sizeof(int));
*(p_arr +4) = 901;
printf("\n\ncalloc 申请到的空间使用:\n");
for(int i=0; i<LEN; i++)
{
printf("%p , %d \n",(p_arr+i),*(p_arr+i));
}
printf("calloc last - start = %d\n",(p_arr+LEN -1 - p_arr));
free(p_nums);
free(p_arr);
return 0;
}
console log:
malloc 申请到的空间使用:
00520d30 , 5383256
00520d34 , 5377296
00520d38 , 1766203502
00520d3c , 11
00520d40 , 1347243843
00520d44 , 1380275285
00520d48 , 1162690894
malloc last - start = 6
calloc 申请到的空间使用:
00520d58 , 0
00520d5c , 0
00520d60 , 0
00520d64 , 0
00520d68 , 901
00520d6c , 0
00520d70 , 0
calloc last - start = 6