我正在调试一个在低内存情况下失败的程序,希望有一个C++程序能够消耗大量内存。任何指针都会有所帮助!
我正在调试一个在低内存情况下失败的程序,希望有一个C++程序能够消耗大量内存。任何指针都会有所帮助!
您是否在Windows平台上(看起来可能不是 :))?如果您正在使用Windows系统,AppVerifier 有一个低内存仿真模式。请参阅“低资源仿真测试”。
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
涂覆大块是行不通的。
您需要编写自己的new/delete版本以按命令失败。
像这样的东西:
#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
编写一个C++应用程序,创建一个巨大的数组。
我知道这是一种内存泄漏,但指针会有所帮助 :)
int main()
{
for(;;)
{
char *p = new char[1024*1024];
}
// optimistic return :)
return 0;
}