Search code examples
cpointersmemory-managementstructfree

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


Ì used to make sure a pointer was not null before freeing it, so I would normally destroy dynamically created structs like this:

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

But CERT MEM34 suggests that since free() accepts null pointers, I could as well write

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

Is that correct?


Solution

  • Yes, passing NULL (a null-pointer constant) to free() is perfectly valid.

    Quoting C11, chapter §7.22.3.3, (emphasis mine)

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