是否有必要在 free() 之前检查指针是否为空

Is it necessary to check whether a pointer is null before free()

Ì 用于确保指针在释放之前不为空,所以我通常会像这样销毁动态创建的结构:

Node *destroy_node(Node *node) {
    if (node) {
        free(node);
    }
    return NULL;
}

但是CERT MEM34建议因为 free() 接受空指针,我也可以写

Node *destroy_node(Node *node) {
    free(node);
    return NULL;
}

对吗?

是的,将 NULL(空指针常量)传递给 free() 是完全有效的。

引用 C11,章节 §7.22.3.3,(强调我的

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. [...]

是的,将 NULL 传递给 free 是空操作。

摘自n1570(C11终稿):

7.22.3.3 The free function Synopsis
1 #include void free(void *ptr);
Description
2 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. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
Returns
3 The free function returns no value.