c - 为什么 malloc 使用零大小?

标签 c pointers memory malloc

<分区>

这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{

   char* p;
   p = (char*)malloc(0);
   scanf("%s", p);
   printf("%s", p);
   free(p);
}

有人可以向我解释为什么我通过终端输入的每个词都会打印给用户吗?我有 malloc(0)。当我尝试 scanf 时不应该给我一个 segmentation fault 吗?

编辑

为什么这会给我一个编译错误:

p = malloc(sizeof(char) * 2)

当我试图避免 (void*)

error: cannot initialize a variable of type 'char *' with an rvalue of type 'void *'

最佳答案

malloc 的 C 标准明确指定:

If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer.

对于 malloc 的返回值:

If size is 0, either a null pointer or a unique pointer that can be successfully passed to free() shall be returned. Otherwise, it shall return a null pointer and set errno to indicate the error.

关于 scanf 调用的段错误,这纯粹是基于环境的实现和运行时行为,只是运气而不是什么,下次是运行,它可能因段错误而崩溃。

关于c - 为什么 malloc 使用零大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33346622/

相关文章:

c - 我的缓冲区有问题,我的 C 程序中的所有线程都不是很大

pointers - 游戏训练器如何更改内存中的动态地址?

c 访问不同翻译单元中的数据成员

c++ - 指向具有函数 C++ 的数据成员的指针

c++ - C++编程中的缓存是什么?

c - 将变量放在特定地址会生成大型二进制文件

c - 在diskperf中获取分区详细信息

c - 分别对待 Makefile 中的一个对象

c - 使用 "inline"调用约定的 "fastcall"函数的性能影响

C++ 在 .size() 之后丢失 vector 元素