linux poison RSS
linux poison Email

Tool for Detecting Memory Management Problems in Programs - Valgrind

Valgrind is a powerful tool for detecting memory management problems in programs. The kinds of problems it can detect are often very difficult to find by other means and often cause difficult to diagnose crashes. Valgrind can be used with existing executables without recompiling or relinking, although the output it produces will be much more useful if you have compiled with the -g flag.

Valgrind Capabilities
Valgrind is basically an x86 emulator that checks all reads and writes of memory, intercepts all calls to allocate and deallocate memory. The memcheck tool of valgrind (which is the main tool and the only one covered in this chapter) can detect the following:

 * Use of uninitialized memory
 * Reading/writing memory after it has been free'd
 * Reading/writing off the end of malloc'd blocks
 * Reading/writing inappropriate areas below the stack.
 * Memory leaks
 * Mismatched use of malloc/new/new[] vs free/delete/delete[]
 * Overlapping src and dst pointers in memcpy() and related functions
 * Doubly freed memory
 * Passing unaddressable bytes to a system call

Valgrind Installation:
Open the terminal and type following commands to install valgrind
sudo apt-get install valgrind
Using Valgrind
Here is the simple C Program having some memory leaks
#include
#include
int main()
{
char* bufferA = (char*)malloc(10); /* here is the leak */
printf("Hello Valgrid, hope you will find the leak in this program...\n");
return 0;
}

Compile the above code (program) using following command
gcc test.c -o run
Here, run the executable file generated for above code
check here - How To Write, Compile and Execute C Programs under Linux

Now, we wil use the Valgrind to detect the memory leak in above program, use the following command:
valgrind -v --tool=memcheck --leak-check=yes ./run
you should see something like ....


As you can see valgrind was able to detect the memrory leak in our program
Also, if you wanted to know where in your program (line number) is the memeory leaks
Recompile the program with the -ggdb switch
gcc test.c -o run -ggdb
(this inserts some debugging information into the resulting binary executable, valgrind can read this data). Then use valgrind again but with a new switch... output should show you the actual line number where memory leak is present.
valgrind --leak-check=full simple
There are many other options and ways in which you can run valgrind. You can learn more at valgrind website, especially the FAQ. Also note that there are graphical frontends to valgrind, among them alleyoop, a front-end using the Gnome libraries.



0 comments:

Post a Comment

Related Posts with Thumbnails