Leon
Leon

Reputation: 364

When does malloc() in C return NULL?

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

Answers (2)

Alberto
Alberto

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.

Check the documentation

Upvotes: 1

chux
chux

Reputation: 153348

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:

  1. Out-of-memory in the machine (not enough bytes)
  2. Out-of-memory for the process (OS may limit space per process)
  3. Out of memory handles (Too many allocations, some allocators has this limit)
  4. Too fragmented (Enough memory exist, but allocator can't/does not want to re-organize into a continuous block).
  5. 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?

Upvotes: 4

Related Questions