A Sane generic cleanup?
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 =开发者_JS百科 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.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned char *uchar1 = NULL;
unsigned char *uchar2 = NULL;
unsigned char *uchar3 = NULL;
int result = 0;
if ((uchar1 = malloc(sizeof(*uchar1) * 10)) == NULL) {
fprintf(stderr, "Error: malloc(uchar1);\n");
result = 1;
goto CLEANUP0;
}
if ((uchar2 = malloc(sizeof(*uchar2) * 10)) == NULL) {
fprintf(stderr, "Error: malloc(uchar2);\n");
result = 1;
goto CLEANUP1;
}
if ((uchar3 = malloc(sizeof(*uchar3) * 10)) == NULL) {
fprintf(stderr, "Error: malloc(uchar3);\n");
result = 1;
goto CLEANUP2;
}
/* do something */
free(uchar3);
CLEANUP2:
free(uchar2);
CLEANUP1:
free(uchar1);
CLEANUP0:
return result;
}
精彩评论