Memory leak detection

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)
{
void *mem;
mem = malloc(size);

if ( NULL == mem )
{
/* memory allocation failed, exit the application */
exit(1);
}
else
{
/* 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 >> */
return(mem);
}
}

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 >> */
return();
}
else
{
free(ptr);
/* 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.

Advertisements
This entry was posted in C Section. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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