Hacker News new | past | comments | ask | show | jobs | submit login

If you want "malloc failure is fatal", which I agree is a good idea for a lot of programs, the way to do that is have a wrapper that aborts() if it does, not to just ignore the possibility of error. That way if the unlikely event ever does happen you get an immediate and clear failure, rather than a NULL which might eventually some time later get dereferenced, so if you get a user crash report you don't ever have to spend time debugging "why did this NULL get here in this data structure? was it maybe a memory corruption bug?".

It also means that if you're dealing with untrusted input you have a guard against that data provoking a huge malloc that fails and manages to do something unexpected as a result. Sure, most of the time the "something unexpected" isn't interesting (immediate crash), and there probably ought to have been a range-check on the input data already, but the NULL-check-and-abort means you never have to spend any time thinking about whether the code is the 0.1% "interestingly exploitable" case. Not having to think about a whole class of situations is pretty valuable IME.




An even better reason is that by having an xmalloc() that exits on failure the compiler's code flow analysis will be improved.

That's because it knows it'll be impossible for the return value of that malloc() to be NULL.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: