Ì 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?
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 byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. [...]