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

后端 未结 9 2277
一整个雨季
一整个雨季 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:29

    Does the caller do anything useful with the memory blocks which have been correctly allocated before the failure? If not, the callee should handle the deallocation.

    One possibility to do the cleanup efficiently is using do..while(0), which allows to break where your example returns:

    int func(void **mem1, void **mem2)
    {
        *mem1 = NULL;
        *mem2 = NULL;
    
        do
        {
            *mem1 = malloc(SIZE);
            if(!*mem1) break;
    
            *mem2 = malloc(SIZE);
            if(!*mem2) break;
    
            return 0;
        } while(0);
    
        // free is NULL-safe
        free(*mem1);
        free(*mem2);
    
        return 1;
    }
    

    If you do a lot of allocations, you might want to use your freeAll() function to do the cleanup here as well.

提交回复
热议问题