CS 33: Using valgrind

CS 33: Computer Organization

December 4, 2008

This web page was written by Tia Newhall but has been slightly edited for the CS33 class.

Using valgrind

valgrind is a tool for finding memory access errors to heap memory (memory that is dynamically allocated with new or malloc) in C and C++ programs. Memory access errors are the most difficult bugs to find and to fix. Tools like valgrind can save you days worth of debugging time by quickly pointing you to the source and type of memory access errors in your code. The types of errors it can find include memory leaks, reading uninitialized memory, accessing unallocated memory, and array out-of-bounds errors.

In the class directory for today is a program called memory.c with bad memory access errors. You can use valgrin on this program to find the errors.

Links to on-line valgrind help pages

How to use valgrind on our system

Running valgrind is easy. Just compile your program with -g, then run the executable (for non-interactive programs, you will likely want to re-direct output to a file since valgrind can generate a lot of output):
  % valgrind ./memory

  % valgrind ./memory >& out   # re-direct valgrind (and memory) output to file 'out'

If you look through the out file, you may see memory errors listed like this (each line of valgrind output starts with ==processid==):

==7444== Invalid write of size 1
==7444==    at 0x804841D: main (memory.c:11)
==7444==  Address 0x41b302d is 0 bytes after a block of size 5 alloc'd
==7444==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)
==7444==    by 0x80483F0: main (memory.c:6)
This tells me that in function main, at line 11 in memory.c, my program is writing 1 byte beyond the array that was allocated at line 6 in function main (7744 was the process ID of my running program). If I look at lines 11 and 6 of my program, the error is obvious (after my loop executes, I put a '\0' in position 5 of the array which is beyond the end of array s, on the last iteration):
5	  int i;
6	  char *s = malloc(5 * sizeof(char));
8	  for (i = 0; i < 5; i++) {
9	    s[i] = 65+i;
10	  }
11	  s[i] = '\0';

valgrind Links

valgrind manual (local copy) includes complete users manual
valgrind HOWTO See the "Usage" section for more information on using valgrind.