Valgrind is a a programming tool suite used for debugging, profiling and detection of memory leaks which are quiet common in C,C++ programs. Detecting memory leaks is done by ‘memcheck’ tool ,which by other means is a very difficult task to do .
To detect a memory leak using ‘Valgrind’ ,let us take an example code which does memory leak .For Example
Here in the example
1) in function ‘f‘ a char * variable ‘k’ is declared and memory block of 100 bytes are allocated to it from the heap. That means , the variable ‘k’ resides on stack and it contains the address of a memory block which is there in heap .
2) the function ‘f’ tries to write in a memory block which has not been allocated to it .That is
when we write
k = 10 ;
we are trying to access the memory byte which lies at an offset of 105 from the ‘k‘ . This memory byte was not allocated to ‘k‘ , hence can lead to serious untrackable bug and mysterious behaviour of the program . When the code is compiled using ‘gcc’ not even a single warning is given , forcing the programmer to believe that the function behaves normally.
Apart from this the when the function ‘f’ returns to the ‘main’ function , the stack frame where the local variables of function ‘f’ (for example ‘k’) gets deallocated, so in this case the value in ‘k‘ ( the address of the 100 byte block) gets lost and thus memory leak occur. For this again, compiler can’t generate error or warning messages.
So for coping with these kind of problems ,valgrind can be used.
Using Valgrind for detecting memory leaks
For using Valgrind the program has to be compiled with ‘-g’ option
gcc – g ‘program_name’.c
then the ‘Valgrind’ program can be used to generate usefull information
valgrind –leak-check=yes ./a.out
For example for the above piece of code it will generate meassages as
Here in above messages,
1) In ==5124== , 5124 is the process id . It is not that important
2) Display a stack trace showing where the problem occured. It can be usefull in large complex code.
3) Error messages show memory addresses involved as the second component.
Memory leaks can be analysed by analysing the error messages
This Dynamic analysis tool is usefull in detecting memory bugs and memory leakage.