65.9K
CodeProject is changing. Read more.
Home

A simple trick to find memory leaks that worked for me

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

May 1, 2013

CPOL

1 min read

viewsIcon

14903

downloadIcon

103

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:  

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

Declaring an instance:

//
#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:

#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:

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

How to turn off this trace:

//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.