c - 我怎么能初始化一个分配了零字节的指针呢?

标签 c pointers memory malloc

<分区>

我知道 malloc(size_t size) 分配 size 字节并返回指向已分配内存的指针。 .

那么,为什么当我将零字节分配给整数指针 p 时,我仍然能够初始化它?

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

int main()
{

        int *p = malloc(0);
        *p = 10;

        printf("Pointer address is: %p\n", p);
        printf("The value of the pointer: %d\n", *p);

        return 0;
}

这是我的程序输出,我预计会出现段错误。

Pointer address is: 0x1ebd260
The value of the pointer: 10

最佳答案

malloc(0) 的行为是实现定义的,它将返回一个指针或NULL。根据 C 标准,您不应在请求零大小空间时使用 malloc 返回的指针1)

取消引用 malloc(0) 返回的指针是未定义的行为,其中包括程序可能执行不正确(崩溃或静默生成不正确的结果),或者它可能偶然地完全按照程序员的意图进行。


1) 来自 C 标准#7.22.3p1 [已添加强调]:

1 The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation. Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer is returned. 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 - 我怎么能初始化一个分配了零字节的指针呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54394817/

相关文章:

c - 判断一棵树是否为二叉搜索树

c++ - 在 GPU 上调用函数时可以避免使用 __device__ 限定符吗?

c++ - 成员函数指针的静态成员数组

c++ - 如何在主机内存上分配 OpenCL 缓冲区的一半,在设备内存上分配另一半?

swift - AV 视频 URL 在内存中保留多长时间?

c - 存储大小未知

c - 超出翻译限制是否是未定义的行为,是否有检查工具可以找到它?

c - 最大和连续子数组使用递归直接输出结果

c - C 中的二维数组和指针 - 如何访问元素?

字符数组显示为空,试图附加第二个字符串