My blog has moved!

You should be automatically redirected in 6 seconds. If not, visit
http://www.mattdturner.com/wordpress
and update your bookmarks.

AdSense

Pages

Sunday, April 17, 2011

Using the Debugging Tool Valgrind

Valgrind is an excellent, and sometimes necessary, tool for debugging troublesome programs. According to Valgrind’s website, the program can “automatically detect many memory management and threading bugs, avoiding hours of frustrating bug-hunting, making your programs more stable. You can also perform detailed profiling to help speed up your programs”.

Valgrind contains a variety of tools for use while debugging. The program can be used to debug a wide variety of programming languages including, but not limited to, C, C++, Java, Perl, Python, Fortran, Ada, etc. Using these tools, you can:

  • Detect memory errors (using the tool Memcheck)
  • Make programs run faster (using the cache and branch-prediction profilerCachegrind)
  • Detect thread errors (using the tool Helgrind and/or DRD)
  • Profile heap usage (using the tool Massif and/or DHAT)


How to Use Valgrind’s Memcheck Tool


Possibly the best thing about Valgrind is the fact that it is very easy to use. There is only 1 thing that you need to do in order to prepare your program for use with Memcheck; compile your program with the -g and -O0 compiler flags. That’s it. Now all you have to do is run your program using valgrind.


Here is an example of how to run a program using Valgrind’s Memcheck tool (example copied from Valgrind User Manual):



If you normally run your program like this:
myprog arg1 arg2
Use this command line to run the program with valgrind:
valgrind --leak-check=yes myprog arg1 arg2



Your program will run a lot slower (around 20-30 times slower) than normal, and it will use a lot more memory.




Example Run


Here is an example program (again taken from the Valgrind User Manual). The file is called a.c.





Running the program with Valgrind provides memory leak messages similar to those shown below:

Some things to note about the output:

  • The 19182 is the process ID
  • The “Invalid write...” tells you what kind of error it is. Here, the program wrote to memory that it should not have
  • Below the first line is the stack trace telling you where the problem occurred.
Valgrind is available for download here.
Here is a direct link to the User Manual.

0 comments:

Post a Comment