Visual C ++: can I limit heap size?

I have a problem with the application that I am debugging. Sustainable memory usage is several hundred megabytes. Sometimes (after a few hours) it goes into a state where its memory usage increases to many gigabytes. I would like to be able to stop the program as soon as this happens when using memory.

If control passes through my own code, I can catch excessive memory usage with this code:

bool usingTooMuchMemory() { PROCESS_MEMORY_COUNTERS pmc; if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) return pmc.WorkingSetSize > 0x80000000u; // 2GB working set return false; } 

This does not help me, because I need to check the size of the working set in the right place. I really want the program to crash into the first malloc or new , which accepts either a working set or a heap size over some threshold. And ideally, I would like it to do a bunch of CRT with minimal overhead, because the library likes to allocate a huge number of small blocks.

The suspicious code is in a DLL running in a thread created by my calling code. The DLL binds statically to a CRT and has no special heap management. I have source code for a DLL.

Any ideas? Am I missing something?

+4
source share
3 answers

You can set memory reallocation and allocation interception using _ CrtSetAllocHook .

+4
source

You can connect the HeapAlloc function that malloc calls internally using the Detours library.

+1
source

http://msdn.microsoft.com/en-us/library/aa366778%28v=vs.85%29.aspx

If you clear the IMAGE_FILE_LARGE_ADDRESS_AWARE flag in the VS linker options, the program heap will be limited to 2 GB and should crash if attempts are made to obtain memory that moves it to this limit.

+1
source

Source: https://habr.com/ru/post/1347058/


All Articles