Search code examples
cmemory-managementmalloc

Under what circumstances can malloc return NULL?


It has never happened to me, and I've programming for years now.

Can someone give me an example of a non-trivial program in which malloc will actually not work?

I'm not talking about memory exhaustion: I'm looking for the simple case when you are allocating just one memory block in a bound size given by the user, lets say an integer, causes malloc to fail.


Solution

  • Yes.

    Just try to malloc more memory than your system can provide (either by exhausting your address space, or virtual memory - whichever is smaller).

    malloc(SIZE_MAX)
    

    will probably do it. If not, repeat a few times until you run out.