top | item 45435368

(no title)

jcupitt | 5 months ago

`free(NULL);` will crash on some platforms that gcc supports, I believe.

discuss

order

lelanthran|5 months ago

> `free(NULL);` will crash on some platforms that gcc supports, I believe.

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".

jibal|5 months ago

It's in C89 (I was on the standards committee, X3J11).

SAI_Peregrinus|5 months ago

Then it's in violation of the C standard, at least as of C11 (I didn't check C99 or C89).

> 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

jibal|5 months ago

> `free(NULL);` will crash on some platforms that gcc supports, I believe.

No, of course it won't. `free(NULL)` has been a noop ever since C89 (and before, for that matter).

unwind|5 months ago

That feels like a "citation needed", since that would be very clear violation of the C spec and thus a rather serious bug in the standard library for that platform.

mrheosuper|5 months ago

can we just do `if(*ptr == NULL) return;` ?

inkyoto|5 months ago

If «ptr» is not a valid pointer, an attempt to dereference it (i.e. *ptr) will most assuredly crash the process with a SIGSEGV.

jibal|5 months ago

> can we just do `if(*ptr == NULL) return;` ?

No, certainly not, but you can do

`if(ptr == NULL) return;`

which is correct but unnecessary since `free` is required to do that check.