如何释放失败的重新分配内的malloc [英] how to free malloc inside failed realloc

查看:68
本文介绍了如何释放失败的重新分配内的malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个结构:

typedef struct person_st{
   char *first_name, *last_name;
   int id;
   Date birthday;  
}*pPerson, Person;

让我说我重新分配sizeof(Person)*(++n)几次. 在每个结构内部,我还为first_namelast_name分配了空间.

lets say i reallocate sizeof(Person)*(++n) few times. inside each struct i also allocate space for the first_name and last_name.

假设在我使用realloc的某个时候会出现分配失败,那么处理所有first_namelast_name分配的最安全/最智能的方法是什么?在Person结构重新分配失败之后,还有办法释放它们吗?

assuming that at some point there will be allocation failure while i use realloc, what is the safest/smartest way to handle all the first_name and last_name allocations? its there still a way to free them after the realloctaion failure of the Person struct?

谢谢.

推荐答案

失败的重新分配不会干扰原始数据,因此您仍然可以引用旧数据(始终假设您保留了旧指针,因为失败的重新分配会返回null)

a failed realloc will not disturb the original data , so you can still refer to the old data (always assuming you kept the old pointer given that the failed realloc will return null)

这篇关于如何释放失败的重新分配内的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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