c pointer, how to free it/them into a function

前端 未结 5 1892
小鲜肉
小鲜肉 2020-12-17 07:02

This is my code:

#include 
#include 
#include 

void getinfo(unsigned int a, unsigned int b, char **pStr);

in         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 07:22

    This is more of a general C language advice than a specific answer, but it's too long to go in comment.

    The usual way to write C in the presence of dynamic resource management is to goto suitable labels which are followed by the relevant deallocation calls:

    int f(int n)
    {
        void * p1, * p2, * p3;
        int result = -1;
    
        p1 = malloc(n);
    
        if (!p1) goto END0;
        if (n % 2) goto END1;
    
        p2 = malloc(3 * n);
    
        if (!p2) goto END1;
        if (n % 7 == 0) goto END2;
    
        p3 = malloc(7 * n + 8);
    
        if (!p3) goto END2;
    
        if (do_useful_stuff(p1, p2, p3) == -1) goto END3;
        result = compute_more_stuff(p1, p2, p3);
    
    END3:
        free(p3);
    END2:
        free(p2);
    END1:
        free(p1);
    END0:
        return result;
    }
    

    The alternative is to split up your code into very small functions that do only one thing at a time and handle resource allocation in an ad-hoc fashion:

    int small_function(void ** p)
    {
        void * q = malloc(13);
    
        if (some_init(&q) == -1)
        {
            free(q);    // ad-hoc exit management
            return -1;
        }
    
        int n = complex_computation(q);
        free(q);
        return n;
    }
    

提交回复
热议问题