Memory Management


Understanding memory is a critical to systems programming. These slides provide a quick introduction to a process's memory layout, the libc functions that dynamically allocate memory, and the relationship between virtual and physical memory.

Valgrind

valgrind is an invaluable tool for diagnosing memory problems such as leaks and corruptions. The tool itself is what's called a dynamic binary instrumentor, which means that it takes as input a block of your code's x86 instructions, adds some instrumentation for tracking memory, and then runs the resultant block: in essence, it is Just-in-Time compiling x86 to x86.

Using such a technique, valgrind can provide fine-grained memory analysis. The tradeoff is that programs run much more slowly under valgrind.

The basic usage of valgrind for tracking memory errors is:


      valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./YOUR_PROGRAM YOUR_PROGRAM_ARGS
      

To get the most detailed output from valgrind, you should compile your program with debugging symbols (-ggdb), as in:


      gcc -o foo -ggdb foo.c