Sane通用清理?

时间:2010-08-02 16:37:12

标签: c

我想学习适用于以下场景的通用清理方法。请记住,这只是 - = 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;
}

3 个答案:

答案 0 :(得分:5)

我想我知道你在做什么。像下面这样的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; 
} 

答案 1 :(得分:2)

答案 2 :(得分:1)