在 C 语言中释放一个 NULL 指针是一个好的做法吗?

可能的复制品:
Ptr 为 NULL 的 free (ptr)是否损坏内存?

我正在编写一个 C 函数,它释放一个指针,如果它是 malloc()ed。指针可以是 NULL (在发生错误并且代码没有得到分配任何东西的机会的情况下) ,也可以用 malloc()分配。用 free(ptr);代替 if (ptr != NULL) free(ptr);安全吗?

gcc完全不抱怨,即使是 -Wall -Wextra -ansi -pedantic,但这是好的做法吗?

97685 次浏览

Quoting the C standard, 7.20.3.2/2 from ISO-IEC 9899:

void free(void *ptr);

If ptr is a null pointer, no action occurs.

Don't check for NULL, it only adds more dummy code to read and is thus a bad practice.


However, you must always check for NULL pointers when using malloc & co. In that case NULL mean that something went wrong, most likely that no memory was available.

See http://linux.die.net/man/3/free which states:

If ptr is NULL, no operation is performed.

In my opinion, no, at least not in your case.

If you couldn't allocate memory, you should have checked that WAY before the call of free.

It is good practice to not bother checking for NULL before calling free. Checking just adds unnecessary clutter to your code, and free(NULL) is guaranteed to be safe. From section 7.20.3.2/2 of the C99 standard:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

As noted in the comments, some people sometimes wonder if checking for NULL is more efficient than making a possibly unnecessary function call. However, this:

  • Is a premature micro-optimization.
  • Shouldn't matter. Checking for NULL first even might be a pessimization. For example, if 99% of the time your pointers aren't NULL, then there would be a redundant NULL check 99% of the time to avoid an extra function call 1% of the time.