checking for NULL before calling free

前端 未结 8 640
终归单人心
终归单人心 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:12

    I tend to write "if (p) free(p)" a lot, even if I know it's not needed.

    I partially blame myself because I learned C the old days when free(NULL) would segfault and I still feel uncomfortable not doing it.

    But I also blame the C standard for not being consistent. Would, for example, fclose(NULL) be well defined, I would not have problems in writing:

    free(p);
    fclose(f);
    

    Which is something that happens very often when cleaning up things. Unfortunately, it seems strange to me to write

    free(p);
    if (f) fclose(f);
    

    and I end up with

    if (p) free(p);
    if (f) fclose(f);
    

    I know, it's not a rational reason but that's my case :)

提交回复
热议问题