Detecting memory leaks by overloading malloc

Let us see how to detect leaks by overriding the malloc and free implementations in GNU “” library

Consider the below program which leaks memory,

int main()
void *ptr1 = malloc(10);
void* ptr2 = malloc(50);
void* ptr3 = malloc(70);
void* ptr4 = malloc(123);
//do something
return 0;

When we compile and run the executable, it will run fine, but it will leak memory referenced by ptr2 and ptr4. To find out such leaks in our code we can overload the implementation of malloc() and free() in file as follows.

Write the following source code in alloc.c file
void* malloc(int size)
void* (*fptr)(int);
void* handle = (void*) -1l;
fptr = (void * (*)())dlsym(handle, “malloc”);
if (fptr == NULL)
printf(“Error in locating\n”);
return NULL;
void*ret  = (*fptr)(size);
printf(“Allocated ptr %x %d\n”, ret, size);
return ret;
void free(void* ptr)
void (*fptr)(void*);
void* handle = (void*) -1; //tells dlsym to locate the next symbol
fptr = (void (*)(void*))dlsym(handle, “free”);
if (fptr == NULL)
printf(“Error in locating\n”);
printf(“Deallocated ptr %x\n”, ptr);

compile the above code and create shared library as follows

$gcc -fPIC  -c alloc.c
$gcc -shared -Wl,-soname, -o alloc.o -lc -ld
fPIC flag instructs the compiler to produce position independent code, so that it shall be used for creating dynamic libraries.

After this set the environment variable, LD_LIBRARY_PATH to include the path where library is created.

run the executable file
$ ./a.out
Allocated ptr 82cd008 10
Allocated ptr 82cd018 50
Allocated ptr 82cd050 70
Allocated ptr 82cd0a0 123
Deallocated ptr 82cd050
Deallocated ptr 82cd008

From the above output, by verifying pointer values we can figure out that two allocations are leaked.

The same technique can be used if you wish to extend functionalities provided by any GNU functions by creating wrapper library for the functions which need to be extended.  This will not require any client code changes(code which calls malloc and free in our case) but still the functionality is extended for the client applications.

Syntax for dynamic loading functions can be found at this url

Further Reading


Leave a Reply

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

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