I have the following piece of code:
void f(size_t n) {
int *a = malloc(n * sizeof *a);
if(a == NULL) {
report_error_and_exit();
}
int *b = malloc(n * sizeof *a);
if(b == NULL) {
free(a);
report_error_and_exit();
}
int *c = malloc(n * sizeof *a);
if(c == NULL) {
free(a);
free(b);
report_error_and_exit();
}
/*use a, b, c*/
}
or something along those lines. Basically, I need multiple malloc
s, and all of them mustn't fail.
I was wondering where should I free some of the allocated memory. As the function gets longer and bigger checking for malloc
fails gets more messy.
A possible solution I was thinking was doing something like the following:
void f(size_t n) {
int *a = malloc(n * sizeof *a);
if(a == NULL) {
goto malloc_fail;
}
/*...*/
malloc_fail:
free(a);
free(b);
/*...*/
report_error_and_exit();
}
however the use of goto
is discouraged.
I am wondering what is the appropriate solution to this.