M
Matt Garman
I was wondering what conventions people use for error handling in a
function while avoiding memory leaks at the same time.
I write a lot of functions that end up looking like the following:
int my_func() {
char *a, *b;
int x;
a = malloc(some_number);
x = another_function(a);
if (x == ERROR_CONDITION) {
free(a);
return ERROR;
}
x = func_that_mallocs(&b);
if (x == ERROR_CONDITION) {
free(a);
free(b);
return ERROR;
}
free(a);
free(b);
return NO_ERROR;
}
As you can see, I essentially have a lot of redundant code. Plus,
this code could easily become a maintenance headache. Basically, I
often do a malloc(), perform some calculations or other
administrativia, maybe do some more malloc(), perform calculations,
etc. At each step along the way, I do error checking (I'm trying to
write robust code). If an error occurs, I need to exit the function,
but I also need to free any malloc'ed memory.
Is there a general strategy for dealing with this kind of scenario?
It seems like a goto might be useful here. Are there any other "nice"
conventions (readable, maintainable, etc)?
Thanks,
Matt
function while avoiding memory leaks at the same time.
I write a lot of functions that end up looking like the following:
int my_func() {
char *a, *b;
int x;
a = malloc(some_number);
x = another_function(a);
if (x == ERROR_CONDITION) {
free(a);
return ERROR;
}
x = func_that_mallocs(&b);
if (x == ERROR_CONDITION) {
free(a);
free(b);
return ERROR;
}
free(a);
free(b);
return NO_ERROR;
}
As you can see, I essentially have a lot of redundant code. Plus,
this code could easily become a maintenance headache. Basically, I
often do a malloc(), perform some calculations or other
administrativia, maybe do some more malloc(), perform calculations,
etc. At each step along the way, I do error checking (I'm trying to
write robust code). If an error occurs, I need to exit the function,
but I also need to free any malloc'ed memory.
Is there a general strategy for dealing with this kind of scenario?
It seems like a goto might be useful here. Are there any other "nice"
conventions (readable, maintainable, etc)?
Thanks,
Matt