MYF

[RA] Ch37.3 Memory Checker: valgrind's memcheck

Reading Assignment: All of Programming Chapter 37.3 Memory Checker: valgrind’s memcheck

Valgrind is a collection of tools, which are designed so that more can be added if desired. However, we are primarily interested in memcheck which is default tool, and will do the checking that we require.

To valgrind your program, run the valgrind command to give it your program name as an argument. If your program takes command line arguments, simply pass them as additional arguments after your program’s name. For the most benefits, you should compile debugging information in your program. (pass the -g or -ggdb3 option to gcc).

The valgrind user’s manual: http://valgrind.org/docs/manual/manual.html

Uninitialized Values

Valgrind’s memcheck tool explicitly tracks the validity of every bit in the program, and can tell us about the use of uninitialized values. By default, memcheck will tell you when you use of an uninitialized value, however, these errors are limited to certain uses.

We can find the uninitialized value with --track-origins=yes and properly initialize it.

Invalid Reads/Writes

Valgrind’s memcheck tool will also perform stricter checking of memory accesses than normally occurs when you run your program.

Valgrind with gdb

What we would like is the ability to run gdb and valgrind together, and have valgrind tell gdb when it encounters an error, giving control to gdb. We can do that with valgrind options --vgdb=ful --vgdb-error=0, then valgrind will stop on the first error it encounters and give control to gdb.

The combination of valgrind and gdb is quite powerful, and gives you the ability to run some new commands, via the monitor command. For example, if we are trying to debug pointer related errors and want to know what variables still point at a particular memory location, we can do use the monitor who_points_at command.

Dynamic Allocation Issues

If you have memory leaks, you will want to run with the --leak-check=full option. When you do so, memcheck will report the location of each allocation which was not freed.

Note that when running valgrind’s memcheck with gdb, you can run the leak checker at any time with the monitor command monitor leak_check full reachable any.

memcheck.h

Valgrind provides header files, such as memcheck.h which contains a variety of macros for exactly this purpose. For example, we could change the function we were using earlier as an example of uninitialized values to

1
2
3
4
5
6
void f(int x){
int y;
int z = x + y;
VALGRIND_CHECK_MEM_IS_DEFINED(&z, sizeof(z));
printf("%d\n", z);
}

Other Valgrind Tools

The valgrind tool Helgrind is designed to check for a variety of errors related to multi-threaded programming. See http://valgrind.org/docs/manual/hg-manual.html