So I have a function which is like a constructor for my structure:
MyStructure* CreateMyStructure(...)
{
MyStructure *my_structure;
double *data;
int *colind, *rowptrs;
data = malloc(sizeof(double)*N);
if (data == NULL) { return(NULL); }
colind = malloc(sizeof(int)*N);
if (colind == NULL) { free(data); return(NULL); }
rowptrs = malloc(sizeof(int)*K);
if (rowptrs == NULL) { free(colind); free(data); return(NULL); }
my_structure = malloc(sizeof(my_structure));
if (my_structure == NULL) {
free(rowptrs); free(colind); free(data);
return(NULL);
}
return(my_structure);
}
This pattern is reoccurring in a lot of the codebase, so I am trying to come up with something cleaner. I thought about creating some macros like these:
#define CHECK_MALLOC1(var, dep1) \
do { \
if (var == NULL) { free(dep1); return(NULL); } \
} while(0)
#define CHECK_MALLOC2(var, dep1, dep2) /* pattern continues */
However, I decided against them because I do not want to change the control flow inside a macro. Is there an alternative pattern that would help reduce repetition without sacrificing someones ability to understand what is going on?