在调用 free 之前检查 NULL [英] checking for NULL before calling free
问题描述
许多 C 代码释放指针调用:
Many C code freeing pointers calls:
if (p)
free(p);
但是为什么呢?我认为 C 标准说 free
函数在给定 NULL 指针的情况下不会做任何事情.那么为什么要进行另一次显式检查?
But why? I thought C standard say the free
function doesn't do anything given a NULL pointer. So why another explicit check?
推荐答案
构造:
free(NULL);
在 C 中一直很好,回到由 Dennis Ritchie 编写的原始 UNIX 编译器.预标准化,一些糟糕的编译器可能没有正确地使用它,但是现在任何没有标准化的编译器都不能合法地称自己为 C 语言的编译器.使用它通常会导致代码更清晰、更易于维护.
has always been OK in C, back to the original UNIX compiler written by Dennis Ritchie. Pre-standardisation, some poor compilers might not have fielded it correctly, but these days any compiler that does not cannot legitimately call itself a compiler for the C language. Using it typically leads to clearer, more maintainable code.
这篇关于在调用 free 之前检查 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!