Visual C++:可以限制堆大小吗?
我正在调试的应用程序出现问题。稳态内存使用量为几百兆字节。有时(几个小时后)它会进入内存使用量飙升至数千兆字节的状态。我希望能够在内存使用发生这种情况时立即停止该程序。
当控制权通过我自己的代码时,我可以使用如下代码捕获过多的内存使用:
bool usingTooMuchMemory()
{
PROCESS_MEMORY_COUNTERS pmc;
if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc))
return pmc.WorkingSetSize > 0x80000000u; // 2GB working set
return false;
}
这对我没有帮助,因为我需要在正确的点测试工作集大小。我真的希望程序在工作集或堆大小超过某个阈值的第一个 malloc
或 new
时中断。理想情况下,我希望由 CRT 堆本身以最小的开销完成此操作,因为该库喜欢分配大量的小块。
可疑代码位于由我的调用代码创建的线程中运行的 DLL 中。 DLL 静态链接到 CRT,并且没有特殊的堆管理。我有DLL的源代码。
有什么想法吗?我错过了一些明显的东西吗?
I have a problem with an application I'm debugging. Steady state memory usage is a few hundred megabytes. Occasionally (after several hours) it gets into a state where its memory usage soars to many gigabytes. I would like to be able to stop the program as soon as memory usage this happens.
Where control passes through my own code, I can trap excessive memory use with code like this:
bool usingTooMuchMemory()
{
PROCESS_MEMORY_COUNTERS pmc;
if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc))
return pmc.WorkingSetSize > 0x80000000u; // 2GB working set
return false;
}
This doesn't help me because I need to test working set size at the right point. I really want the program to break on the first malloc
or new
that takes either working set or heap size over some threshold. And ideally I'd like to have this done by the CRT heap itself with minimal overhead because the library likes to allocate huge numbers of small blocks.
The suspect code is in a DLL running in a thread created by my calling code. The DLL links statically to the CRT and has no special heap management. I have source code for the DLL.
Any ideas? Am I missing something obvious?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 _CrtSetAllocHook 设置内存分配和释放挂钩。
You can set memory allocation and deallocation hooks, using _CrtSetAllocHook.
您可以使用 弯路 库。
You can hook the
HeapAlloc
function, which malloc calls internally, by using the Detours library.http://msdn.microsoft.com/en -us/library/aa366778%28v=vs.85%29.aspx
如果清除 VS 链接器选项中的 IMAGE_FILE_LARGE_ADDRESS_AWARE 标志,则程序的堆大小将限制为 2GB,并且如果尝试获得超过该限制的内存。
http://msdn.microsoft.com/en-us/library/aa366778%28v=vs.85%29.aspx
If you clear the IMAGE_FILE_LARGE_ADDRESS_AWARE flag in VS's linker options, the program's heap will be limited to 2GB in size, and should crash if attempts are made to acquire memory that would put it over that limit.