Reputation: 741
in some functions I need to allocate memory with malloc() and have several if..else statements, like the pseudo-code illustrates:
allocate memory
if condition_1
do_stuff
if condition_2
do_more_stuff
else
error
else
error
free allocated memory
return
So I allocate memory at the beginning and it would freed if everything would work well. But currently the error functions only print an error message and exit the porgram. But as I have read often that not freeing memory although when the program exits and the OS handles normally handles the freeing afterwards, it no good style. How can I free the money in a lazy way? Do I have to write an error function that takes every pointer to the memory I have allocated that has to be freed,the pointery may be of different data types? Or should i put free(ptr) before calling the error function? An error function that takes an array of pointer with data type void and freeing than all, would do this the trick?
Upvotes: 3
Views: 3413
Reputation: 13171
Don't use goto. Use a one-time while. Also, if you need an error flag, default it to true instead of false to save code:
...malloc...
err = 1;
do {
...
if <condition> break;
...
if <condition> break;
...
if <condition> break;
...
err = 0;
} while (0);
...free...
if (err) ...
Upvotes: 1
Reputation: 4016
I have two solutions.
You can put a label where you put the call to free
and error
:
void function(void)
{
Memory *p = malloc(sizeof(*p));
if (condition_1) {
do_stuff();
if (condition_2) {
do_more_stuff();
} else {
goto err;
}
} else {
goto err;
}
free(p);
return;
err:
free(p);
error();
}
You can also use a flag to mark an error:
void function(void)
{
Memory *p = malloc(sizeof(*p));
bool err = false;
if (condition_1) {
do_stuff();
if (condition_2) {
do_more_stuff();
} else {
err = true;
}
} else {
err = true;
}
free(p);
if (err)
error();
}
I think that the second solution looks best in this case but both of them work equally well.
Upvotes: 4
Reputation: 3316
From what I understand you care about freeing all the memory when you exit the program because of error but dont want to handle all the pointers manually.
Here is an interesting thought, write a function allocMemory that returns the result of malloc but also puts the pointer into a linked list, then freeMemory that removes it from the list, and finally release all function that iterates over the list and frees all the pointers. Use the allocMemory and freeMomory function instead of malloc and free, and call the freeMemory function in case of error.
Upvotes: 1