关于 realloc 函数的困惑

Confusion about realloc function

我使用 this 参考阅读了 C 中的动态内存分配。

那个文件说的:

realloc() should only be used for dynamically allocated memory. If the memory is not dynamically allocated, then behavior is undefined.

如果我们使用 realloc() 这样的东西:

int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

根据那个参考,这个程序是未定义的,因为指针 ptr 不是动态分配的。

但是,如果我使用类似的东西:

int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

根据该参考,它是否也是未定义的行为?

我认为第二种情况不会调用未定义的行为。我说得对吗?

第一个案例有未定义的行为,第二个没有。在第一种情况下,ptr 的值是不确定的。因此,将该值传递给 realloc 或任何函数本身是未定义的。

另一方面,由于 realloc 在传递空指针值时具有明确定义的行为(就像调用 malloc1,第二段代码是完全合法的(除了你没有 free 任何东西的事实)。


1 7.22.3.5 realloc函数/p3

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.

在第一种情况下,程序几乎肯定会在 segmentation fault 之前完成,因为在堆中创建的用于查找段的链表不一致,在第二种情况下,您首先使用 NULL 调用 realloc参数,这意味着,是一个相当于 malloc(size)

的调用

man realloc 说:

   void *malloc(size_t size); 
   void *realloc(void *ptr, size_t size);

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

唯一的权威参考是标准文档。 n1570(最新的C11标准)有如下说法:

§7.22.3.5 realloc 函数,p3:

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. [...]

因此,您的第二个示例定义明确。

  1. 第一种情况显然是未定义的行为,因为我们不知道 ptr 指向哪里或者 ptr 持有什么那时。而c标准说7.20.3.4.2 realloc函数

The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size.

所以第一种情况是未定义的行为。

  1. 在第二种情况下编译器知道 ptr 有什么所以它是有效的但是 realloc() 根据 7.20.3.4.3 将作为 malloc() 的 realloc 函数

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.