logoalt Hacker News

rstuart4133last Friday at 7:49 AM2 repliesview on HN

Yes `foo` is a pointer.

`free(NULL)` is harmless in C89 onwards. As I said, programmers freeing NULL caused so many issues they changed the API. It doesn't help that `malloc(0)` returns NULL on some platforms.

If you are writing code for an embedded platform with some random C compiler, all bets on what `free(NULL)` does are off. That means a cautious C programmer who doesn't know who will be using their code never allows NULL to be passed to `free()`.

In general, most good C programmers are good because they suffer a sort of PTSD from the injuries the language has inflicted on them in the past. If they aren't avoiding passing NULL to `free()`, they haven't suffered long enough to be good.


Replies

lelanthranlast Friday at 10:09 AM

> That means a cautious C programmer who doesn't know who will be using their code never allows NULL to be passed to `free()`.

If your compiler chokes on `free(NULL)` you have bigger problems that no LLM (or human) can solve for you: you are using a compiler that was last maintained in the 80s!

If your C compiler doesn't adhere to the very first C standard published, the problem is not the quality of the code that is written.

> If they aren't avoiding passing NULL to `free()`, they haven't suffered long enough to be good.

I dunno; I've "suffered" since the mid-90s, and I will free NULL, because it is legal in the standard, and because I have not come across a compiler that does the wrong thing on `free(NULL)`.

random_human_last Friday at 8:11 AM

So what would be the best practice in a situation like that? I would (naively?) imagine that a null pointer would mostly result from a malloc() or some other parts of the program failing, in which case would you not expect to see errors elsewhere?

show 1 reply