Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 683
Gentoo Avatar asked Dec 17 '09 18:12

Gentoo


4 Answers

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.

like image 183
dirtybird Avatar answered Oct 21 '22 17:10

dirtybird


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
like image 9
Nick Dixon Avatar answered Oct 21 '22 19:10

Nick Dixon


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
like image 7
Martin York Avatar answered Oct 21 '22 18:10

Martin York


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

like image 3
RHicke Avatar answered Oct 21 '22 18:10

RHicke