Simulating low memory using C ++

I am debugging a program that fails in a low memory situation and would like the C ++ program to simply consume a lot of memory. Any pointers will help!

+5
source share
6 answers

Large block coverage will not work.

  • Depending on the OS, you are not limited to the actual physical memory, and unused large chunks can potentially be simply replaced with a disk.
  • It is also very difficult to make your memory fail when you want it to fail.

What you need to do is write your own version of the new / delete command, which is not executed by the command.

Something like that:

#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
+7

Windows ( ... , :)) Windows, AppVerifier . . .

+12

Unix Linux, 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
+9

++,

+3

, , :)

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

, . ?

On Linux, the command ulimitis probably what you want.

You probably want to use ulimit -vit to limit the amount of virtual memory available to your application.

0
source

All Articles