To write robust C program, how do you avoid too many different free () combinations?

We do like this:

void *a = NULL;
void *b = NULL;
void *c = NULL;
a = malloc(1);
if (!a) goto errorExit;
b = malloc(1);
if (!b) goto errorExit;
c = malloc(1);
if (!b) goto errorExit;

return 0;
errorExit:
//free a null pointer is safe.
free(a);
free(b);
free(c);
return -1;

Using goto is not a bad thing, in my opinion. Using it for resource cleanup is just right for it.

Source code as famous as the Linux kernel uses the technique.

Just don't use goto to go backwards. That leads to disaster and confusion. Only jump forward is my recommendation.


As previously mentioned by Zan Lynx use goto statement.

You can also alloc larger chunk of memory for further use.

Or you can invest your time to develop something like memory pool.