Thursday, 5 December 2013

Valgrind To Check Memory Leak

Valgrind is very useful tool for checking memory leak and heap summary in program running in linux system.You will find this tool easily. Just use 'apt-get install valgrind' for that.You can do it by yourself in few minutes.Follow the procedure mentioned  below and you are done !!

Make one simple program 'memory_leak.c'.

#include<stdio.h>
#include<stdlib.h>

void main()
{
    int *p;
    p=(int *)malloc(sizeof(int));
   
    if(p == NULL)
    {
        printf("out of memory\n");
    }
    *p = 5;
    printf("%d\n",*p);
   
    free(p);            
}

We will check two scenarios. 
1.Comment out line free(p) in program.---free(p) -> //free(p)

   Type following command in your linux terminal. 

$ gcc -o memory_leak memory_leak.c
$ valgrind --tool=memcheck --leak-check=yes ./memory_leak




Here we are using memcheck tool of valgrind for finding heap summary and checking leaks if possible.You can find more about it in manual page of valgrind.

2.Remove comments from line free(p) in program.---//free(p)-> free(p)

   Type the same commands shown above in terminal.

$ gcc -o memory_leak memory_leak.c
$ valgrind --tool=memcheck --leak-check=yes ./memory_leak




You can see that in first scenario valgrind will show leak summary and will inform user that there will be lost of bytes as there is '1 allocs, 0 frees', while in second scenario there is no possibilities of any leaks because all the blocks allocated were freed.
You can also make logs of output by using 'log-file' option.


No comments:

Post a Comment