Read Memcheck: a memory error detector, from the Valgrind user manual. Focus on sections 4.2 and 4.5:

Valgrind has been very useful for catching memory bugs in our C/C++ code. It would be great to understand how it works at a high level, what bugs it can find, and what bugs it may miss.

To get some hands-on experience, try to compile the following C program evil.c (attu recommended) and run it with Valgrind.

#include <stdlib.h>
int main(int argc, char **argv) {
  if (argc != 2) return -1;
  int idx = atoi(argv[1]);
  char *a = malloc(100);
  char *b = malloc(1000);
  a[idx] = 0; // BUG: if idx < 0 or idx >= 100
  free(a);
  free(b);
  return 0;
}

See if Valgrind complains with input 100.

$ gcc -o evil -O0 -g evil.c
$ valgrind ./evil 100

Change the input from 100 to 500 and run Valgrind again.

$ valgrind ./evil 500
Question
  • Does Valgrind complain during the two runs? Guess why or why not.

Turn in your answer as part of Exercise 13.

The code example is adapted from Google’s AddressSanitizer paper (see below).

Further readings