如果将 NULL 和大小 0 传递给 realloc() 会怎样?

What if NULL and size 0 are passed to realloc()?

是否定义了行为实现?如果 NULL 和 size == 0 传递给 realloc():

int main(void)
{
    int *ptr = NULL;

    ptr = realloc(ptr, 0);

    if(ptr == NULL)
    {
        printf("realloc fails.\n");
        goto Exit;
    }

    printf("Happy Scenario.\n");

Exit:
    printf("Inside goto.\n");

return 0;
}

上面的代码应该打印"realloc fails",对吧?但它不是吗?我在某处读到,对 realloc 的调用也可能 return NULL。什么时候发生?

重新分配(3)文件:

If ptr is NULL, then the call is equivalent to malloc(size), for all values of size

malloc(3) 文档:

If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be success‐fully passed to free().

所以是的,它是实现定义的,您将获得 null 或您可以释放的指针。

来电

realloc(NULL, size);

等同于

malloc(size);

当被要求分配 0 字节时 malloc() 做了什么有点不清楚,标准没有说明。我认为是 implementation-defined。它基本上 "doesn't matter";它要么是 returns NULL,要么是 returns 一个可以合法访问零字节的指针,它们非常相似。两者都可以传递给 free().

此行为是实现定义的。

来自C standard

第 7.22.3.5 节(realloc):

3 If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

因此 realloc(NULL, 0)malloc(0)

相同

如果我们再看第 7.22.3.4 节 (malloc):

2 The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

3 The malloc function returns either a null pointer or a pointer to the allocated space.

标准没有说明传入 0 时会发生什么。

但是如果你看 Linux man page:

The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

它明确指出返回值可以被释放但不一定是NULL。

相比之下,MSDN表示:

If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.

所以对于 MSVC,你不会得到 NULL 指针。