Cad Cam Development

Debugging memory leaks in VS C++


How memory leaks information is displayed

Memory leaks can fund a C/C++ programmer a real nightmare. You can protect yourself by providing the following code to each your c/cpp source code file. It’s good to make a VS macro so that you could include it faster and provide it to your every project you’re working on.

Code Snippet 1

#ifdef _DEBUG
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW

Code Snippet 2

#ifdef _DEBUG

How does it works?

Suppose you are connecting to a COM Object and you missed CComObject<T> Release at the end or you don’t free whole memory you’ve allocated to a pointer. Inserting this magic lines will help you to debug memory leaks because proper information will be shown at output window. It will exchange your normal mode of ‘new’ allocation model to those defined above. You can insert there any information you want but file name and line number is exactly what you need. Check any further predefined macros on msdn if you want. All in one: you have to provide code snippet 1 to all source files you’re compiling and code snippet 2 to start memory leak detection. Code snippet 2 should be invoked as early as possible (somewhere at the beginning of main) because this invokes a process of collecting memory leaks. And that’s all: unmanaged memory leaks are detected and displayed after debugging session is finished in an output window. See the photo at the beginning of the post to see results.

There is also another way of detecting memory leaks. Check Valgrind on the internet. After some steps it is also possible to use it in Visual Studio.

If you require any further information, there’s a quite nice artice on the msdn about memory leak detection which gave me knowledge to implement it to my projects as a “standard feature” and write this post.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s