概述
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("nbefore malloc %pn",p); p = (char *)malloc(size); if(!p) { printf("malloc error n"); return -1; } //len of malloc(0) printf("len of malloc(%d) is %d ,the ture is %dn",size,strlen(p),malloc_usable_size(p)); //the first member printf("the first member of malloc(%d) is %p:%d n",size,p,*p); //set the first member *p = 10; printf("set the first member of malloc(%d) is %p:%d n",size,p,*p); //memcpy memset(p,'