Is this a good way to free memory?

后端 未结 5 710
忘掉有多难
忘掉有多难 2020-12-14 13:58

The function for freeing an instance of struct Foo is given below:

void DestroyFoo(Foo* foo)
{
    if (foo) free(foo);
}

A

5条回答
  •  借酒劲吻你
    2020-12-14 14:27

    What your collegue suggests will make the code "safer" in case the function is called twice (see sleske comment...as "safer" may not mean the same for everybody...;-).

    With your code, this will most likely crash:

    Foo* foo = malloc( sizeof(Foo) );
    DestroyFoo(foo);
    DestroyFoo(foo); // will call free on memory already freed
    

    With your collegues's version of the code, this will not crash:

    Foo* foo = malloc( sizeof(Foo) );
    DestroyFoo(&foo);
    DestroyFoo(&foo); // will have no effect
    

    Now, for this specific scenario, doing tmpFoo = 0; (within DestroyFoo) is enough. memset(tmpFoo, 0, sizeof(Foo)); will prevent crash if Foo has extra attributes that could be wrongly accessed after memory is released.

    So I would say yes, it may be a good practice to do so....but it's only a kind of security against developers who have bad practices (because there's definitely no reason to call DestroyFoo twice without reallocating it)...in the end, you make DestroyFoo "safer" but slower (it does more stuff to prevent bad usage of it).

提交回复
热议问题