将 realloc() 返回的地址分配给同一个指针是一种好的编码习惯吗? [英] Is it good coding practice to assign the address returned by realloc() to the same pointer?

查看:18
本文介绍了将 realloc() 返回的地址分配给同一个指针是一种好的编码习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些网站上看到了一些与 realloc() 相关的代码,如下所示.

I saw some code related to realloc() on some sites as below.

int *p = (int *)malloc(sizeof(int) * 10);
p = (int *)realloc(p, 100);

但正如标准所说,如果 realloc 失败,原始块保持不变并返回 NULL.

But as the standard says, if realloc fails, the original block is left untouched and it returns NULL.

所以如果 realloc 失败,从上面的例子中,我们将失去释放 p 的能力.谁能告诉我将 realloc() 返回的地址分配给同一个指针是一种好的编码习惯吗?

So if realloc fails, from above example, we will lose the ability to free p. Can any one please let me know is it good coding practice to assign the address returned by realloc() to the same pointer?

推荐答案

您是正确的,直接将 realloc 的返回值分配给原始指针的唯一副本是一种不好的做法.如果 realloc 失败,您不仅会失去 free 内存的能力(我认为这是较小的问题);您还会丢失指针所指向的数据.

You are correct that directly assigning the return value of realloc to your only copy of the original pointer is a bad practice. Not only do you lose the ability to free the memory if realloc failed (I would call this the lesser issue); you also lose the data that your pointer pointed to.

对于某些程序,这可能无关紧要(例如,如果您只是要在分配失败时终止并中止整个操作,这可能是也可能不是可接受的做法,这本身就是一个完整的主题),但总的来说您需要先将 realloc 的结果存储到一个单独的临时变量中,并且只有在检查成功后才覆盖原始指针变量.

For some programs this may not matter (e.g. if you're just going to terminate and abort the entire operation on allocation failures, which may or may not be acceptable practice, and which is a whole topic in itself) but in general you need to first store the result of realloc to a separate temp variable, and only overwrite the original pointer variable after you check that it succeeded.

这篇关于将 realloc() 返回的地址分配给同一个指针是一种好的编码习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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