Where should I call Free() function?

前端 未结 4 1132
Happy的楠姐
Happy的楠姐 2020-12-22 07:42

For example:


In A.c :

Head init(){
Head treeHead;
treeHead = malloc(sizeof (struct TreeHead));
treeHead->Root = malloc(sizeof (struct TreeNode)         


        
相关标签:
4条回答
  • 2020-12-22 07:51

    There's no hard and fast rule here except that you can call free() before init() returns because then the return pointer will be invalid.

    This is a great example of how C++ is so much better for this kind of thing. If you have to use C, then you could call free() from either location, depending on what seems to make the best sense.

    0 讨论(0)
  • 2020-12-22 08:03

    I would define a function in A.c:

    void freeHead(Head head){
       free(head->Root);
       free(head);
       return;
    }
    

    Then call it in appropriate places in B.c:

    freeHead(head);
    
    0 讨论(0)
  • 2020-12-22 08:13

    free gets called when you no longer want or need the allocated memory, i.e. when you are done with the TreeHead and TreeNode. It would be silly to free the memory in init(), because you haven't done anything with it yet.

    0 讨论(0)
  • 2020-12-22 08:16

    I would place the free() call in the module which did the corresponding malloc()/calloc() call. In your case, "A.c" provided a function to allocate memory for a Head object. There should be a corresponding function to delete the memory that was previously allocated also in "A.c".

    It does not make sense to me to free the memory given to me from non-standard libraries (i.e., third party code) when I'm the consumer of that library. There may be other memory allocated to that object that I don't necessarily have access to, especially for opaque data types.

    e.g.,

    MyType.c:

    typedef struct _MyType
    {
        char *name; /* fields are "private" */
        ...
    } *MyType; /* opaque type "MyType" */
    
    MyType MyType_create(void)
    {
        MyType ret = malloc(sizeof *ret);
        ret->name = malloc(...);
        return ret;
    }
    
    void MyType_delete(MyType obj)
    {
        free(obj->name);
        free(obj);
    }
    

    Program.c:

    typedef void *MyType;
    
    int main(void)
    {
        MyType obj1 = MyType_create(); /* we have an "instance" of MyType */
        MyType_delete(obj1);           /* delete it */
    
        MyType obj2 = MyType_create(); /* we have an "instance" of MyType */
        free(obj2);  /* uh oh, what happened to the memory allocated for obj2->name? leak */
    }
    

    See also another example.

    0 讨论(0)
提交回复
热议问题