Why malloc memory in a function and free it outside is a bad idea?

前端 未结 5 697
傲寒
傲寒 2021-02-02 18:23

if this is a bad idea, how to allocate memory in the function?

5条回答
  •  日久生厌
    2021-02-02 18:57

    It's not a bad idea if you just keep it consistent in your own style.

    A good approach is to pass the allocated memory to the caller that can then free it when its done. Something like this:

    void my_new(char **obj) {
        *obj = malloc(somesize);
    }
    

    and then call this from your function like this:

    char *obj;
    
    my_new(&obj);
    
    /* work on obj */
    
    free(obj)
    

提交回复
热议问题