What is the best way to free memory after returning from an error?

后端 未结 9 2257
一整个雨季
一整个雨季 2020-12-13 22:00

Suppose I have a function that allocates memory for the caller:

int func(void **mem1, void **mem2) {
    *mem1 = malloc(SIZE);
    if (!*mem1) return 1;

            


        
9条回答
  •  一生所求
    2020-12-13 22:23

    This is a readable alternative:

    int func(void **mem1, void **mem2) {
      *mem1 = malloc(SIZE);
      *mem2 = malloc(SIZE);
      if (!*mem1 || !*mem2) {
        free(*mem2);
        free(*mem1);
        return 1;
      }
      return 0;
    }
    

提交回复
热议问题