Reputation: 79665
Is there a function available that can get the number of blocks of memory that are currently allocated on the heap? It can be Windows/Visual Studio specific.
I'd like to use that to check if a function leaks memory, without using a dedicated profiler. I'm thinking about something like this:
int before = AllocatedBlocksCount();
foo();
if (AllocatedBlocksCount() > before)
printf("Memory leak!!!");
Upvotes: 2
Views: 634
Reputation: 9113
There are several ways to do it (specific to the CRT that comes with Microsoft Visual Studio.)
One way would be to use the _CrtMemCheckpoint()
function before and after the call you are interested in, and then compare the difference with _CrtMemDifference()
.
_CrtMemState s1, s2, s3;
_CrtMemCheckpoint (&s1);
foo(); // Memory allocations take place here
_CrtMemCheckpoint (&s2);
if (_CrtMemDifference(&s3, &s1, &s2)) // Returns true if there's a difference
_CrtMemDumpStatistics (&s3);
You can also enumerate all the allocated blocks using _CrtDoForAllClientObjects()
, and a couple of other methods using the debug routines of the Visual C++ CRT.
Notes:
<crtdbg.h>
header._DEBUG
macro defined.)Upvotes: 4