Reputation: 364
Malloc returns a null when heap memory is insufficient OR when heap is super fragmented.
What I would like to know is that if there are OTHER circumstances when malloc() returns a NULL?
PS:Under what circumstances can malloc return NULL? didn't seem to answer my question
Upvotes: 1
Views: 3062
Reputation: 12909
If for some reason, the memory that you ask to malloc can't be allocated or sometimes if you ask for 0
memory, it returns NULL
.
Upvotes: 1
Reputation: 153348
When does
malloc()
in C returnNULL
?
malloc()
returns a null pointer when it fails to allocate the needed space.
This can be due to:
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?
Upvotes: 4