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