For example,
I need to malloc two pieces of memory, so:
void *a = malloc (1);
if (!a)
return -1;
void *b = malloc (1);
if (!b)
{
free (a);
return -1;
}
Notice if the second malloc fails, I have to free “a” first. The problem is, this can be very messy if there are many such malloc’s and error checking’s, unless I use the notorious “goto” clause and carefully arrange the order of free’s along with the labels:
void *a = malloc (1);
if (!a)
goto X;
void *b = malloc (1);
if (!b)
goto Y;
return 0; //normal exit
Y:
free (a);
X:
return -1;
Do you have any better solution to this situation? Thanks in advance.
We do like this: