malloc(0)实际上有效吗?

可能重复:
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 *** 

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

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

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

从C标准:

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

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