I read that on Unix systems, malloc can return a non-NULL pointer even if the memory is not actually available, and trying to use the memory later on will trigger an error. Since I cannot catch such an error by checking for NULL, I wonder how useful it is to check for NULL at all?
On a related note, Herb Sutter says that handling C++ memory errors is futile, because the system will go into spasms of paging long before an exception will actually occur. Does this apply to malloc as well?
Quoting Linux manuals:
You ought to check for
NULLreturn, especially on 32-bit systems, as the process address space could be exhausted far before the RAM: on 32-bit Linux for example, user processes might have usable address space of 2G – 3G as opposed to over 4G of total RAM. On 64-bit systems it might be useless to check themallocreturn code, but might be considered good practice anyway, and it does make your program more portable. And, remember, dereferencing the null pointer kills your process certainly; some swapping might not hurt much compared to that.If
mallochappens to returnNULLwhen one tries to allocate only a small amount of memory, then one must be cautious when trying to recover from the error condition as any subsequentmalloccan fail too, until enough memory is available.The default C++ operator
newis often a wrapper over the same allocation mechanisms employed bymalloc().