Is this a good way to free memory?

后端 未结 5 682
忘掉有多难
忘掉有多难 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:44

    Unfortunately, this idea is just not working.

    If the intent was to catch double free, it is not covering cases like the following.

    Assume this code:

    Foo *ptr_1 = (FOO*) malloc(sizeof(Foo));
    Foo *ptr_2 = ptr_1;
    free (ptr_1);
    free (ptr_2); /* This is a bug */
    

    The proposal is to write instead:

    Foo *ptr_1 = (FOO*) malloc(sizeof(Foo));
    Foo *ptr_2 = ptr_1;
    DestroyFoo (&ptr_1);
    DestroyFoo (&ptr_2); /* This is still a bug */
    

    The problem is that the second call to DestroyFoo() will still crash, because ptr_2 is not reset to NULL, and still point to memory already freed.

提交回复
热议问题