Monday, February 28, 2011

How to detect memory leaks in C/C++ program ?

Let us first see, How malloc and free works.

int * p = (int*)malloc(sizeof(int));
//malloc allocates memory and returns address to p. Let us say memory address 1000 is returned by malloc.

while freeing the memory, we will make use of the same address.

free(p); //free the memory address pointed by p [ in our case the memory address is 1000]

To detect memory leaks in a multiple file:

The concept is we have to use a Linked List to store the every malloc information.

Let us say malloc() is called in 100th line in 1.C.

At the time of malloc, We need to store the following informations in a linked list.
1.address returned by the malloc() fn
2.CPP filename [To get the c/cpp filename, we can use _FILE_ macro which will gives the cpp filename]
3.Line number at which malloc is called [_LINE_ macro gives us the line number]

Whenever we are freeing the memory, we need to check the linked list whether memory to be freed is available in where we stored the malloc() information.
if it is available in a linked list, then we need to delete that particular node and then free the memory.


Line No:50: int * p = malloc(sizeof(int));
Line No:70: int* q = malloc(sizeof(int));
End of the program:
//we forget to free the p;

For the above program, we will create the linked list with two nodes to represent two malloc info in 1.cpp.
while freeing the memory, the address to be freed will be checked with the linked list. if any node in a linked list matches, then we will remove that entry.
At the end of the program,Linked list will contains information about whichever pointer is not freed from memory.


No comments: