查看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指针呢?当然,实际情况到底如何,还得看代码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
int alloc_memory(char *p , int size)
{
printf("\nbefore malloc %p\n",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 %d\n",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,'\0',12);
memcpy(p,"01234567890123456789",12);
printf("after memcpy , the content is %s len is %d , the ture is %d \n",p,strlen(p),malloc_usable_size(p));
free(p);
p = NULL;
printf("\n");
}
int main(int argc ,char **argv)
{
int size = -1;
char *p = NULL;
//malloc(0)
size = 0;
alloc_memory(p,size);
//malloc(5)
size = 5;
alloc_memory(p,size);
//malloc(20)
size = 20;
alloc_memory(p,size);
return 0;
}
测试结果如下:
root@ubuntu:~/unix_net/interview# ./test
before malloc (nil)
len of malloc(0) is 0 ,the ture is 12
the first member of malloc(0) is 0x8b20008:0
set the first member of malloc(0) is 0x8b20008:10
after memcpy , the content is 012345678901 len is 15 , the ture is 12
before malloc (nil)
len of malloc(5) is 0 ,the ture is 12
the first member of malloc(5) is 0x8b20008:0
set the first member of malloc(5) is 0x8b20008:10
after memcpy , the content is 012345678901 len is 15 , the ture is 12
before malloc (nil)
len of malloc(20) is 0 ,the ture is 20
the first member of malloc(20) is 0x8b20018:0
set the first member of malloc(20) is 0x8b20018:10
after memcpy , the content is 012345678901 len is 12 , the ture is 20
从测试结果来看,可以得出以下几个结论:
1. malloc(0)在我的系统里是可以正常返回一个非NULL值的。这个从申请前打印的before malloc (nil)和申请后的地址0x9e78008可以看出来,返回了一个正常的地址。
2. malloc(0)申请的空间到底有多大不是用strlen或者sizeof来看的,而是通过malloc_usable_size这个函数来看的。---当然这个函数并不能完全正确的反映出申请内存的范围。
3. malloc(0)申请的空间长度不是0,在我的系统里它是12,也就是你使用malloc申请内存空间的话,正常情况下系统会返回给你一个至少12B的空间。这个可以从malloc(0)和malloc(5)的返回值都是12,而malloc(20)的返回值是20得到。---其实,如果你真的调用了这个程序的话,会发现,这个12确实是”至少12“的。
4. malloc(0)申请的空间是可以被使用的。这个可以从*p = 10;及memcpy(p,"01234567890123456789",12);可以得出。
虽然malloc(0)没有发现在现实中有什么意义,但是既然有些人非要我们回答,那我们还是有必要探究一下的,否则你只有被pass掉了。关于这个问题的讨论很值得,因为它让我对技术更加感兴趣,不经意间学到了其他的知识。
如果大家有什么不同意见,欢迎跟帖讨论,谢谢!