我知道 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.