我正在阅读 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/