by jcupitt · 1y ago · 0 comments
I'm pretty certain that `free(NULL)` is part of the C99 standard, so compiler vendors have had 25 years to address it.
If your `free(NULL)` is crashing on a certain platform, you probably have bigger problems, starting with "Compiler that hasn't been updated in 25 years".
> 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.
Emphasis mine
>If ptr is a null pointer, no action occurs.
No, of course it won't. `free(NULL)` has been a noop ever since C89 (and before, for that matter).
Embedded systems are an exception, though. They may not have a MMU, and in such a case the operation will succeed.
>so that if a pointer is checked after it has already been dereferenced, it cannot be null.
sound to me that if i've never deref the pointer anytime before(e.g the null check is at the beginning of function), the compiler won't remove this check.
> This option is enabled by default on most targets. On AVR and MSP430, this option is completely disabled.
No, certainly not, but you can do
`if(ptr == NULL) return;`
which is correct but unnecessary since `free` is required to do that check.