c - malloc(0) 真的有效吗?

标签 c memory malloc allocation

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/

相关文章:

c - 释放指向指针结构的指针

c++ - 如何将 malloc 返回的指针视为多维数组?

c - 内存映射库的文件名 osx

c++ - OpenCV:内存损坏

c - 手动控制 GTK 小部件重绘滴答率

c - 提取 HTTP post 数据

c - 内存消耗?

c - malloc 边界大小 : is there a performance difference

c - error : request for member 'next' in something not a structure or union. 是什么意思?

c - 字符串连接