how to free malloc inside failed realloc

戏子无情 提交于 2019-12-24 07:47:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!