c - malloc(0) 的行为

标签 c pointers

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/

相关文章:

c - 正确释放结构

c - popen() 的安全版本?

c - 如何从char函数返回字符串

c++ - 我应该删除函数中的局部指针吗? (C++)

c++ - 检查数组元素是否为空

c - 这些示例(* 和 &)之间有什么区别?

c - request_mem_region() 实际上做了什么以及何时需要?

c - 在 c 中设置自定义日期的问题

c - strerror_r 无效

c - 如何使用 char** ? (指向字符数组的指针)