checking for NULL before calling free

前端 未结 8 660
终归单人心
终归单人心 2020-12-03 13:45

Many C code freeing pointers calls:

if (p)
  free(p);

But why? I thought C standard say the free function doesn\'t do anything

8条回答
  •  星月不相逢
    2020-12-03 14:17

    if (p)
        free(p);
    

    why another explicit check?

    If I write something like that, it's to convey the specific knowledge that the pointer may be NULL...to assist in readability and code comprehension. Because it looks a bit weird to make that an assert:

    assert(p || !p);
    free(p);
    

    (Beyond looking strange, compilers are known to complain about "condition always true" if you turn your warnings up in many such cases.)

    So I see it as good practice, if it's not clear from the context.

    The converse case, of a pointer being expected to be non null, is usually evident from the previous lines of code:

    ...
    Unhinge_Widgets(p->widgets);
    free(p); // why `assert(p)`...you just dereferenced it!
    ...
    

    But if it's non-obvious, having the assert may be worth the characters typed.

提交回复
热议问题