Reputation: 347
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
Reputation: 264381
Allcoating big blocks is not going to work.
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
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
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
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
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