There are many memory leak detection tools available in market today.Some of the most commonly used tools are wdb,gdb, valgrind etc…
In this posting, i will be explaining on, how to write code with logging enabled, so that the debug logs generated by running the application can be parsed for memory leaks. This method of memory leak detection has following advantages when compared to other tools
1. no need of building debug version of binary
2. no need of third party memory leak detection tools
3. no need to run the application under the influence of third party tool,so no degradation in application performance
This method of memory leak dection can be used for detecting
1. memory leaks
2. double frees
3. memory locations which are not allocated and application is trying to free (invalid frees)
4. heap usage of application through out it’s life
malloc() is the call used for memroy allocation and free() is the call for freeing the memory.
define the following in one of the header files.
#define MALLOC(size) user_malloc(size, __FILET__, __LINE__)
#define FREE(ptr) user_free(ptr, __FILET__, __LINE__)
void * user_malloc(int size, const char *fileName, int lineNumber)
mem = malloc(size);
if ( NULL == mem )
/* memory allocation failed, exit the application */
/* log the mem address, size, fileName and lineNumber to a file */
/* eg. log in the file as below */
/* << allocated of size in file at line number >> */
void user_free(void *ptr, const char *fileName, int lineNumber)
if ( NULL == ptr )
/* this is double free */
/* log to the same file as used in user_malloc() function */
/* eg. log as below */
/* <<freeing null pointer in file at line number >> */
/* log the freed memory address to the same file as used in user_malloc() function */
/* eg. log as below */
/* << freed in file at line number >> */
ptr = NULL;
Instead of using malloc() and free() for memory allocation and freeing, use MALLOC() and FREE(). So all the allocations and memory freeing will be logged into a file.
File in which all the allocations and deallocations are entered can be parsed and any memory leaks/double free’s can be detected. Simillar user functions can be implemented for realloc() and calloc().
Since parsing of the debug logs can be done with any scripting language (perl), this method is platform independent.