malloc & calloc 的区别

malloccalloc都可以用来申请内存空间,从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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值