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

查看:211
本文介绍了将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);

但是,正如标准所说,如果重新分配失败,则原始块将保持不变,并返回NULL.

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

因此,如果重新分配失败,从上面的示例中,我们将失去释放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的结果存储到一个单独的temp变量中,并且仅在检查它是否成功后才覆盖原始指针变量.

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天全站免登陆