sashoalm
sashoalm

Reputation: 79665

Get number of blocks allocated on the heap to detect memory leaks

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

Answers (1)

yzt
yzt

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:

  • All these are in the <crtdbg.h> header.
  • They obviously work only on Windows and when compiling with VC.
  • You need to set up CRT debugging and a few flags and other things.
  • These are rather tricky features; make sure to read the relevant parts of the MSDN carefully.
  • These only work in debug mode (i.e. linking with the debug CRT and the _DEBUG macro defined.)

Upvotes: 4

Related Questions