checking for NULL before calling free

前端 未结 8 666
终归单人心
终归单人心 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 13:56

    There are two distinct reasons why a pointer variable could be NULL:

    1. because the variable is used for what in type theory is called an option type, and holds either a pointer to an object, or NULL to represent nothing,

    2. because it points to an array, and may therefore be NULL if the array has zero length (as malloc(0) is allowed to return NULL, implementation-defined).

    Although this is only a logical distinction (in C there are neither option types nor special pointers to arrays and we just use pointers for everything), it should always be made clear how a variable is used.

    That the C standard requires free(NULL) to do nothing is the necessary counterpart to the fact that a successful call to malloc(0) may return NULL. It is not meant as a general convenience, which is why for example fclose() does require a non-NULL argument. Abusing the permission to call free(NULL) by passing a NULL that does not represent a zero-length array feels hackish and wrong.

提交回复
热议问题