Possible Duplicate:
what’s the point in malloc(0)?
为什么 malloc(0) 实际上返回一个有效的写入指针?
char *str = NULL;
str = (char*)malloc(0); // allocate 0 bytes ?
printf("Pointer of str: %p\n", str);
strcpy(str, "A very long string ...................");
printf("Value of str: %s", str);
free(str); // Causes crash if str is too long
输出:
Pointer of str: 0xa9d010
Aborted
Value of str: A very long string ...................
何时 str
更短,然后它就可以正常工作。
顺便说一句:为了编译,我使用了带有“-D_FORTIY_SOURCE=0 -fno-stack-protector”的 GCC
*** glibc detected *** ..: free(): invalid next size (fast): 0x0000000000a9d010 ***
最佳答案
取消引用 malloc(0)
返回的指针是未定义的行为。
来自 C 标准:
(C99, 7.20.3p1) "If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object."
关于c - malloc(0) 真的有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487183/