实际上malloc(0)这个语法是对的,也确实分配了内存,但内存空间是0,就是说返回指针是不能用的。malloc(0)的返回值可能是NULL也可能不是NULL,和实参为一个正整数时没什么区别。如果返回值不为NULL,也应该用free()函数释放。malloc(0)唯一不同的地方就是,就算你申请内存成功,即malloc(0)返回值不为NULL,你也没法使用这块内存。
《C语言参考手册》上说“如果请求的长度为0,则标准C语言函数返回一个null指针或不能用于访问对象的非null指针。”
void *malloc(size_t size);
...
malloc() allocates size bytes and returnsa pointer to the allocated memory. The memory is not cleared. If sizeis 0, then malloc() returns either NULL, or a unique pointer value thatcan later be successfully passed to free().
char *ptr; if(int pp = (strlen(ptr=(char *)malloc(0))) == 0) puts("Got a null pointer"); else puts("Got a valid pointer");
char *ptr; if(int pp = (sizeof(ptr=(char *)malloc(0))) == 4) puts("Got a null pointer"); else puts("Got a valid pointer");
如果求ptr的strlen的值和sizeof的值,该代码的输出是"Got a null pointer"。
A size_t value is always positiveeven if you pass a negative value to malloc.The negative value is converted to an unsigned value of type size_t which leads to a huge positive value.
Example:
char *p = malloc(-2);
is equivalent to:
char *p = malloc(SIZE_MAX- 1); // SIZE_MAX is the maximum
// size_tvalue