我想学习一种适用于以下场景的通用清理方法.请记住,这只是 - = 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;
}
Run Code Online (Sandbox Code Playgroud)
我想我知道你在做什么.像下面这样的Somehing可以更容易地确保您正确地管理资源.我相信这是一个不需要被视为有害的情况.
编辑反映了Summy0001优秀的观察并修复了错误价值的回报.
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |