logoalt Hacker News

johncolanduoniyesterday at 5:23 AM2 repliesview on HN

No non-embedded libc will actually return NULL. Very, very little practical C code actually relies only on specified behavior of the spec and will work with literally any compliant C compiler on any architecture, so I don’t find this particularly concerning.

Usefully handling allocation errors is very hard to do well, since it infects literally every error handling path in your codebase. Any error handling that calls a function that might return an indirect allocation error needs to not allocate itself. Even if you have a codepath that speculatively allocates and can fallback, the process is likely so close to ruin that some other function that allocates will fail soon.

It’s almost universally more effective (not to mention easier) to keep track of your large/variable allocations proactively, and then maintain a buffer for little “normal” allocations that should have an approximate constant bound.


Replies

jclulowyesterday at 5:45 AM

> No non-embedded libc will actually return NULL

This is just a Linux ecosystem thing. Other full size operating systems do memory accounting differently, and are able to correctly communicate when more memory is not available.

show 1 reply
jenadineyesterday at 9:39 AM

> No non-embedded libc will actually return NULL.

malloc(-1) should always return NULL. Malloc returns NULL if the virtual address space for a given process is exhausted.

It will not return NULL when the system is out of memory (depending on the overcommit settings)