malloc(0)实际上有效吗?

时间:2013-01-23 18:52:46

标签: c memory malloc allocation

  

可能重复:
  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更短时,它就会正常工作。

BTW:为了编译,我使用GCC“-D_FORTIY_SOURCE = 0 -fno-stack-protector”

*** glibc detected *** ..: free(): invalid next size (fast): 0x0000000000a9d010 ***

3 个答案:

答案 0 :(得分:4)

取消引用malloc(0)返回的指针是未定义的行为。

来自C标准:

  

(C99,7.20.3p1)“如果请求的空间大小为零,则行为是实现定义的:返回空指针,或者行为就像大小是非零值一样,除了返回的指针不得用于访问对象。“

答案 1 :(得分:2)

  

为什么malloc(0)实际上会返回一个有效的写指针?

它不会返回有效的写入指针。它返回不使用的有效指针。或者它也可以返回NULL,因为C标准指定这种情况是实现定义的。

答案 2 :(得分:1)

malloc()应该返回一个void *指针。它忠实地做到了。但是当你取消引用它时会导致UB。