就像我在http://www.cnblogs.com/wuyuegb2312/p/3219659.html 文章中评论的那样,我也碰到了被提问这个malloc(0)的返回值问题,虽然感觉这样做在实际中没有任何意义,但既然被提问到了,那总得给点答复。当时的回答是“返回一个NULL指针”。
就像@五岳查看man结果的一样,我也查看了,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 successfully passed to free().这句话翻译起来,就是传个0的话,返回值要么是NULL,要么是一个可以被free调用的唯一的指针。那是不是这篇文章中说的,通过这句话“
if(int pp = (strlen(ptr=(char *)malloc(0))) == 0)
”来判断是不是NULL指针呢?当然,实际情况到底如何,还得看代码。
刚看到@garbageMan一篇文章 http://www.cnblogs.com/pmer/p/3222648.html 这样写道:“malloc(0)唯一不同的地方就是,就算你申请内存成功,即malloc(0)返回值不为NULL,你也没法使用这块内存。”那到底是不是就没法使用呢?
我的测试代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> int alloc_memory(char *p , int size) { printf(" before malloc %p ",p); p = (char *)malloc(size); if(!p) { printf("malloc error "); return -1; } //len of malloc(0) printf("len of malloc(%d) is %d ,the ture is %d ",size,strlen(p),malloc_usable_size(p)); //the first member printf("the first member of malloc(%d) is %p:%d ",size,p,*p); //set the first member *p = 10; printf("set the first member of malloc(%d) is %p:%d ",size,p,*p); //memcpy memset(p,'