Gentoo
Gentoo

Reputation: 347

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!

Upvotes: 5

Views: 4505

Answers (6)

Loki Astari
Loki Astari

Reputation: 264381

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

Upvotes: 7

chollida
chollida

Reputation: 7894

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.

Upvotes: 0

Nick Dixon
Nick Dixon

Reputation: 875

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

Upvotes: 9

RHicke
RHicke

Reputation: 3604

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

Upvotes: 3

dirtybird
dirtybird

Reputation: 422

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.

Upvotes: 12

Dmitry
Dmitry

Reputation: 6770

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

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

Upvotes: 2

Related Questions