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