在 NULL 值(或未定义)指针上重新分配 [英] Realloc on NULL-valued (or undefined) pointer

查看:52
本文介绍了在 NULL 值(或未定义)指针上重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#include #include int主(){int* ptr = NULL;ptr = realloc(ptr, 10*sizeof(int));返回0;}

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

int* ptr = NULL;

我有这个:

int* ptr;//没有给 ptr 赋值

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

解决方案

使用 realloc 分配内存是否有危险初始值为 NULL 的 ptr

<块引用>

7.22.3.5

如果 ptr 是空指针,则 realloc 函数的行为类似于 malloc指定大小的函数.

第二部分:

<块引用>

int* ptr;//没有给 ptr 赋值

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

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

<块引用>

否则,如果 ptr 与之前由 a 返回的指针不匹配内存管理功能 [...] 行为未定义

I was reading about realloc and got confused about a point mentioned there. Consider the code below:

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

int main () {

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

Is there any danger in allocating memory with realloc using the initially NULL-valued ptr? If instead of:

int* ptr = NULL;

I had this:

int* ptr; // no value given to ptr

would it be a problem to call realloc using ptr?

解决方案

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

None

7.22.3.5

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

For the second part:

int* ptr; // no value given to ptr

would it be a problem to call realloc using ptr?

If you're using uninitialized pointers then that is a very serious problem indeed since you can't predict what their value will be. The function realloc only works correctly for NULL or values obtained from malloc / realloc.

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

这篇关于在 NULL 值(或未定义)指针上重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆