Tutorial :Simulating low memory using C++


I am debugging a program that fails during a low memory situation and would like a C++ program that just consumes LOT of memory. Any pointers would help!


Allcoating big blocks is not going to work.

  • Depending on the OS you are not limited to the actual physical memory and unused large chunks could be potentially just swap out to the disk.
  • Also this makes it very hard to get your memory to fail exactly when you want it to fail.

What you need to do is write your own version of new/delete that fail on command.

Somthing like this:

#include <memory>  #include <iostream>        int memoryAllocFail = false;    void* operator new(std::size_t size)  {      std::cout << "New Called\n";      if (memoryAllocFail)      {   throw std::bad_alloc();      }        return ::malloc(size);  }    void operator delete(void* block)  {      ::free(block);  }    int main()  {      std::auto_ptr<int>  data1(new int(5));        memoryAllocFail = true;      try      {          std::auto_ptr<int>  data2(new int(5));      }      catch(std::exception const& e)      {          std::cout << "Exception: " << e.what() << "\n";      }  }  > g++ mem.cpp  > ./a.exe  New Called  New Called  Exception: St9bad_alloc  


Are you on the Windows platform (looking at the username...perhaps not :) ) If you are in Windows land, AppVerifier has a low memory simulation mode. See the Low Resource Simulation test.


If you're using Unix or Linux, I'd suggest using ulimit:

bash$ ulimit -a  core file size        (blocks, -c) unlimited  data seg size         (kbytes, -d) unlimited  ...  stack size            (kbytes, -s) 10240  ...  virtual memory        (kbytes, -v) unlimited  


Just write a c++ app that creates a giant array


I know it's a leak, but pointers will help :)

int main()  {      for(;;)      {          char *p = new char[1024*1024];      }      // optimistic return :)      return 0;  }  


A similar question was asked here and htis was my response. How do I force a program to appear to run out of memory?

On Linux the command ulimit is probably what you want.

You'll probably want to use ulimit -v to limit the amount of virtual memory available to your app.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »