C语言malloc(0)问题

来源:互联网 发布:网页代码优化 编辑:程序博客网 时间:2024/05/17 11:03

学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
原创粉丝点击