Home » C++

Easy memory leak detection in C/C++

30 June 2003 11,303 views 2 Comments

Easy memory leak detection in C/C++

The way to do it is to fight fire with fire and create a Singleton class, like this:

#if _DEBUG

#define FINDMEMLEAK(val) _DetectMemoryLeaks::DetectMemoryLeaks(val)

class _DetectMemoryLeaks
{
public:
   static_DetectMemoryLeaks& DetectMemoryLeaks(int val)
   {
      static _DetectMemoryLeaks inst;
      _crtBreakAlloc=val;
      return inst;
   }

   ~_DetectMemoryLeaks()
   {
      _CrtDumpMemoryLeaks();
   }
};

#else

#define FINDMEMLEAK(val)

#endif

To use this class, place it in a header file, and make sure that the very first command in your program is to use the macro defined at the top.

FINDMEMLEAK(-1);

The Singleton class keeps a static instance of itself inside the function "DetectMemoryLeaks", and this instance will be one of the last things to be destroyed, at which point the "_CrtDumpMemoryLeaks" routine is called. Providing the macro is called before any other static instances of other objects are created, this technique will pick up any memory leaks involving them.

If the static objects that are causing the problems are static class members, then declare the above class a static member of the same class, but make sure the declaration is the first member, before the other objects. That way, this class should still be the last to be destroyed. Bare in mind that the order of declaration is important, as usually the compiler will try to destroy the objects in reverse order of creation.

If you enjoyed this article you can make an entry in the guestbook or you can express any concerns or questions by using the contact form here. Thanks!

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

2 Comments »

  • JohnDepther said:

    interesting library ! 5 for the idea
    Does it can catch leaks gdi objects how deleaker for example?

  • AndyN (author) said:

    Hi John,
    Thanks for leaving a comment.

    To be honest, it’s been an age since I wrote this, and I think it’s probably a bit outdated nowadays, what with technology like .NET. Also, since Python is so well integrated into most 3D apps, I find fewer reasons to write C or C++ code anyway.

    As for your question, I’m not sure I understand what you’re asking. Can you clarify?

    Cheers,
    A

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.