int main()
{
char *p;
p = (char* ) malloc(sizeof(char) * 0);
printf("Hello Enter the data without spaces :\n");
scanf("%s",p);
printf("The entered string is %s\n",p);
//puts(p);
}
在编译并运行上面的代码时,即使我们为指针 p 分配了 0 字节内存,程序也能够读取字符串。
语句 p = (char* ) malloc(0)
中实际发生了什么?
最佳答案
malloc()
将返回什么是实现定义的,但使用该指针是未定义的行为。未定义的行为意味着任何事情都可能发生,从程序正常运行到崩溃,所有安全赌注都已关闭。
C99 标准:
7.22.3 内存管理函数
第 1 段:
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/10684595/