关于malloc(0)的返回值问题

关于malloc(0)的返回值问题–这两天的总结与实践篇

就像我在文章中评论的那样,我也碰到了被提问这个malloc(0)的返回值问题,虽然感觉这样做在实际中没有任何意义,但既然被提问到了,那总得给点答复。当时的回答是“返回一个NULL指针”。

就像

if(int pp = (strlen(ptr=(char *)malloc(0))) == 0)

”来判断是不是NULL指针呢?当然,实际情况到底如何,还得看代码。

刚看到@garbageMan一篇文章这样写道:“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(,p);p = (char *)malloc(size);if(!p){printf();return -1;}//len of malloc(0)printf(,size,strlen(p),malloc_usable_size(p));//the first member printf(,size,p,*p);//set the first member*p = 10;printf(,size,p,*p);//memcpymemset(p,,12);memcpy(p,,12);printf(,p,strlen(p),malloc_usable_size(p));free(p);p = NULL;printf();}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;}

测试结果如下:

tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/EXERCISE$ gcc -o malloc malloc.c tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/EXERCISE$ ./mallocbefore malloc (nil)len of malloc(0) is 0 ,the ture is 12the first member of malloc(0) is 0x9e78008:0 set the first member of malloc(0) is 0x9e78008:10 after memcpy , the content is 012345678901len is 15 , the ture is 12before malloc (nil)len of malloc(5) is 0 ,the ture is 12the first member of malloc(5) is 0x9e78008:0 set the first member of malloc(5) is 0x9e78008:10 after memcpy , the content is 012345678901len is 15 , the ture is 12before malloc (nil)len of malloc(20) is 0 ,the ture is 20the first member of malloc(20) is 0x9e78018:0 set the first member of malloc(20) is 0x9e78018:10 after memcpy , the content is 012345678901 len is 12 , the ture is 20tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/EXERCISE$

从测试结果来看,可以得出以下几个结论:

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掉了。关于这个问题的讨论很值得,因为它让我对技术更加感兴趣,不经意间学到了其他的知识。

如果大家有什么不同意见,网站空间,欢迎跟帖讨论,谢谢!

注:—后为新增内容。

总结:为了安全起见,malloc(0)的非NULL返回值,最好不要进行除了free()之外的任何操作!

关于内存管理方面,大家可以参考IBM上的一篇文章:

旅行,重复一个承诺和梦想,听他第二十八次提起童年往事,

关于malloc(0)的返回值问题

相关文章:

你感兴趣的文章:

标签云: