c - 在 NULL 值(或未定义)指针上重新分配

标签 c undefined-behavior realloc

我正在阅读 realloc并对那里提到的一点感到困惑。考虑以下代码:

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

int main () {

    int* ptr = NULL;
    ptr = realloc(ptr, 10*sizeof(int));
    return 0;
}

使用初始 NULL 值的 ptr 通过 realloc 分配内存是否有任何危险?如果不是:

int* ptr = NULL;

我有这个:

int* ptr; // no value given to ptr

使用ptr调用realloc会有问题吗?

最佳答案

Is there any danger in allocating memory with realloc using the initially NULL-valued ptr

7.22.3.5

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

第二部分:

int* ptr; // no value given to ptr

would it be a problem to call realloc using ptr?

如果您使用未初始化的指针,那么这确实是一个非常严重的问题,因为您无法预测它们的值是多少。函数 realloc 仅适用于 NULL 或从 malloc/realloc 获得的值。

Otherwise, if ptr does not match a pointer earlier returned by a memory management function [...] the behavior is undefined

关于c - 在 NULL 值(或未定义)指针上重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12134315/

相关文章:

c++ - C++ 中的移位运算

c - 使用 malloc 和 realloc 时出错

c - 为什么 realloc 会消耗大量内存?

c - 如果我重新分配并且新大小为 0 会发生什么情况。这是否等同于免费?

c++ - const_cast : override a const status

你能帮我了解 fopen ("contact.dll"、 "r");

c - Linux 内核线程

c - 关于字符串长度,终止NUL等

c++ - `x ? 1 : 0` 变成了 40,未定义的行为?

c - C 中的老虎机游戏 - 打印卷轴问题