4

I am currently writing a program that allocates memory in various places. I am interested in seeing how my program behaves when the heap runs out of memory, namely when when malloc() returns NULL.

Is there a compiler option that can let me set the heap size to something very small so I can see what happens immediately? I am using the gcc compiler.

CowZow
  • 1,275
  • 2
  • 17
  • 36
  • Note that, depending on your OS, you can't necessarily assume that `malloc` will actually return `NULL` when you run out of memory. Instead, there's a good chance that you will successfully obtain virtual memory, and then die as soon as you try to actually use it. There's no safe, portable way to handle running out of memory. – ruakh Mar 31 '13 at 17:46

4 Answers4

4

You can specify stack and heap sizes like this:

gcc -Wl,--stack=xxxxx -Wl,--heap=yyyyy ...
Johnny Mnemonic
  • 3,822
  • 5
  • 21
  • 33
2

At least if on Linux you could use ulimit -m <max mem> prior to running your program.

alk
  • 69,737
  • 10
  • 105
  • 255
1

Compile as 32 bit and exhaust the virtual address space by reserving large chunks of memory (you don't need to commit - just reserve (these are Windows terms, I'm sure they have Linux equivalents).

Windows also has Job Objects that you can use to limit memory but maybe the simple VirtualAlloc technique will work.

The nice thing about it is that you can dynamically change the limit, maybe using a timer, to stress the program again and again at random times.

usr
  • 168,620
  • 35
  • 240
  • 369
1

What about replacing malloc & friends with your own code to simulate the condition? I’m not sure about the best way to do it, maybe LD_PRELOAD would work (some example code here).

zoul
  • 102,279
  • 44
  • 260
  • 354