When does malloc() in C return NULL?

淺唱寂寞╮ 提交于 2020-02-05 00:22:27

问题


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


回答1:


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?




回答2:


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



来源:https://stackoverflow.com/questions/59850398/when-does-malloc-in-c-return-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!