问题
I have this struct:
typedef struct person_st{
char *first_name, *last_name;
int id;
Date birthday;
}*pPerson, Person;
lets say i reallocate sizeof(Person)*(++n) few times.
inside each struct i also allocate space for the first_name and last_name.
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?
thanks.
回答1:
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)
回答2:
the best way to call realloc is something like this:
more_people = realloc(people, count * sizeof(Person));
if (!more_people) {
// handle failure
} else {
people = more_people;
}
This way you check the return code from realloc and safely handle the failure
来源:https://stackoverflow.com/questions/42079285/how-to-free-malloc-inside-failed-realloc