When does malloc()
in C return NULL
?
malloc()
returns a null pointer when it fails to allocate the needed space.
This can be due to:
- Out-of-memory in the machine (not enough bytes)
- Out-of-memory for the process (OS may limit space per process)
- Out of memory handles (Too many allocations, some allocators has this limit)
- Too fragmented (Enough memory exist, but allocator can't/does not want to re-organize into a continuous block).
- All sorts of reasons like your process is not worthy of more.
malloc(0)
may return a null pointer. C17/18 adds a bit.
If the size of the space requested is zero, the behavior is implementation-defined:
either a null pointer is returned to indicate an error,
or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
malloc(0)
may return a null pointer. (pre-C17/18)
If the size of the space requested is zero, the behavior is implementation-defined:
either a null pointer is returned,
or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
The "to indicate an error" of C17/18 implies to me that a null pointer return is an error, perhaps due to one of the above 5 reasons and a non-erroring malloc(0)
does not return a null pointer.
I see this as a trend to have p = malloc(n); if (p==NULL) error();
to always be true on error even if n
is 0. Else one might code as if (p==NULL && n > 0) error();
If code wants to tolerate an allocation of zero to return NULL
as a non-error, better to form a helper function to test for n == 0
and return NULL
than call malloc()
.
Conversely a return of non-null pointer does not always mean this is enough memory. See Why is malloc not “using up” the memory on my computer?