C语言malloc(0)问题

学C语言的时候遇到了malloc(0)的坑,原因是:


一些解释:

---------------------------------------------------------------------------------------------------------------------

MSDN上原话是“If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item”
也就是说,如果申请内存大小为0,还是会返回一个有效指针
返回指针为NULL的条件是申请一定大小内存,内存空间不够的时候

----------------------------------------------------------------------------------------------------------------------------------------------

Allocates size bytes of uninitialized storage. If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any object type.

If size is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage)

----------------------------------------------------------------------------------------------------------------------------------------------

 malloc()  allocates  size  bytes and returns a pointer to the allocated
       memory.  The memory is not  cleared.   If  size  is  0,  then  malloc()
       returns  either  NULL, or a unique pointer value that can later be suc-
       cessfully passed to free().

-----------------------------------------------------------------------------------------------------------------------------------------------------------

If the size of the space requested is 0, the behaviour is implementation-dependent; the value returned will be either a null pointer or a unique pointer. 
If size is 0, either a null pointer or a unique pointer that can be successfully passed to free() will be returned. 
-----------------------------------------------------------------------------------------------------------------------------------------------------------

我自己的实际情况是:

在Dev-C++5.5.3中测试时,char * word=(char*)malloc(0); 有时候word是“”,有时候是一堆看不懂的乱码。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值