I would like to learn a generic cleanup approach which applies to a scenario like the following. Please remember that this is just a -=SAMPLE=-.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned char *uchar1, *uchar2, *uchar3;
if ((uchar1 = malloc(sizeof(*uchar1) * 10)) == NULL) {
fprintf(stderr, "Error: malloc(uchar1);\n");
return 1;
}
if ((uchar2 = malloc(sizeof(*uchar2) * 10)) == NULL) {
fprintf(stderr, "Error: malloc(uchar2);\n");
free(uchar1);
return 1;
}
if ((uchar3 = malloc(sizeof(*uchar3) * 10)) == NULL) {
fprintf(stderr, "Error: malloc(uchar3);\n");
free(uchar1);
free(uchar2);
return 1;
}
/* do something */
free(uchar1);
free(uchar2);
free(uchar3);
return 0;
}
I think I know what you’re getting at. Somehing like the following can make it easier to ensure that you correctly manage resources. I beleive that it is one case where goto needn’t be considered harmful.
Edited to reflected Summy0001’s excellent observarion and fix return of wrong value.