I'm struggling to come up with a clean way to handle my allocated memory in C. Suppose I have something like this:
void function(int arg) {
char *foo;
foo = (char *)malloc(sizeof(char) * 100);
int i = func1(arg, &foo);
char *bar;
bar = (char *)malloc(sizeof(char) * 100);
int j = func2(&bar);
free(foo);
free(bar);
}
My problem is that func1
and func2
may encounter error and exit(1)
, so I need to free foo
and bar
when that happens.
If func1
encounters error, I just call free(foo)
and I'll be good. But if func2
encounters error, I cannot just call free(bar)
since I also need to free foo
. This can get really complicated and I feel that this is not the right way to handle memory.
Am I missing anything here? It will be awesome if someone can point me the right direction. Thanks!