如何释放失败的重新分配内的malloc [英] how to free malloc inside failed realloc
问题描述
我有这个结构:
typedef struct person_st{
char *first_name, *last_name;
int id;
Date birthday;
}*pPerson, Person;
让我说我重新分配sizeof(Person)*(++n)
几次.
在每个结构内部,我还为first_name
和last_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_name
和last_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屋!