Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

A simple trick to find memory leaks that worked for me

5.00/5 (4 votes)
1 May 2013CPOL1 min read 14.8K   100  
Title says it all.

Introduction

I love programming with C/C++. As long as there is no pressure from the client I choose to develop with C++, web or desktop. But I always face the problem with memory leaks. Here is a simple trick for how I traced memory leaks on debug. The files are added in the page.  

Using the code

The way I use this is I define an object of the class Allocation. One instance for one module to trace out all the allocation and free. 

How to include and declare the header file:  

C++
#ifdef _DEBUG
#include "dbg.h"
#endif

Declaring an instance:

C++
//
#if defined _DEBUG && _mDEG //_mDEG is defined in dbg.h file
Allocation myalloc("file_name_to_save_your_debug_result.txt");
#endif   

Allocation of memory:

C++
#if defined _DEBUG && _mDEG
        //it might seem too much work. but its much easier to find out a leak after development. 
	char *buf=(char *)myalloc.getMemory(desired_memory_size,__LINE__, __FILE__,"buf");
#else
	char *buf=(char *)malloc(desired_memory_size);
#endif

Freeing memory:

C++
#if defined _DEBUG && _mDEG
	myalloc.memfree((unsigned long)buf);
#else
	free(buf);
#endif

How to turn off this trace:

C++
//just remove the include line of dbg.h

How does it work 

As a matter of fact, I have created a linked list. When I allocate memory, I write down the address, the filename, the line number where the allocation is called, and the variable. When I free the address, I just find the address and free it. When the Allocation instance is destroyed it calls the destructor and writes the rest of the unfreed memory in the specific file at the beginning.  

I have been using this for a while, so far working good for me. Hope it would help you too.

What it won't do

It won't tell you if you overflow a buffer. I.e., if you allocate 10 bytes and use 11 bytes, this one will not tell you.   

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)