malloc和calloc的区别(笔试题)

虽然见过,但是很少用calloc,还是代码量少啊。。。
区别1:函数形式:
void *calloc(
   size_t num,   //numbers of elements
   size_t size   //Length in bytes of each elements
);
void *malloc(
size_t size  //Bytes to alloc
);
区别2:calloc分配内存后会自动初始化为0,而malloc不会。
还有一道题:判断程序能不能执行:
 
 
这个是不能执行的,参数为void说明没有参数。malloc不支持0参数。
若改为:void *p=(void *)malloc(0);在VC6下不会返回空指针,引用网上找的一句C99标准:
If the size of the space requested is zero, the behavior is  implementation defined:   

either a null pointer is returned, or the behavior is as if the size were some  
nonzero value, except that the returned pointer shall not be used to access an object.  
   
如果所请求的空间大小为0,其行为由库的实现者定义:可以返回空指针,也可以让效果跟申请某个

非0大小的空间一样,所不同的是返回的指针不可以被用来访问一个对象。

如果是void *p=(void *)malloc(-1);由于在32位系统size_t被定义为unsigned int,在64位系统被定义
为unsigned long故分配一个很大的数。
但是第二句将一个void*加加,编译出错:“”。我居然想当然
的认为它可以转为int*。。。

转载于:https://www.cnblogs.com/helbhu/archive/2007/12/22/1010664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值