CS31 Weekly Lab: Week 9

Week 9 lab topics:

  1. .h and .c files, scope, extern, static
  2. gdb for C programmers
  3. valgrind

Create a week09 subdirectories in your cs31/weeklylabs directory and copy over some code:
    cd
    cd cs31/weeklylabs
    mkdir week09
    cd week09
    pwd 
    # note you are doing a recursive copy here (-r option):
    cp -r ~newhall/public/cs31/week09/* .
    ls
    Makefile  counter.c  counter.h  gdb_examples/  main.c  valgrind_examples/

.h and .c files, extern, static
The example in the main week09 subdirectory is a program that is defined in two .c files and a .h file containing definitions shared by both.

Let's examine this code, compile and run the program.

GDB for C program debugging
You are now all experts at using gdb to examine IA32 assembly code. Today, we are going to look at some features of gdb for debugging C programs. In particular, looking at a stack trace, moving between frames to examine parameter and argument values, and examining runtime state of a segfaulting program.

Everything you know with setting breakpoints and using the print and examine commands translates to C code. The difference is that you specify C source code functions and line numbers for break points (vs. assembly instruction addresses), you typically use variable names in print and x command expressions, and you use step and next (vs. stepi and nexti) to step through individual C instruction execution.

cd into the gdb_examples subdirectory.

First, run make to build the executables (note they are all compiled with -g).

Let's look through a couple of the example programs in gdb, following along in my GDB Guide.

Valgrind
cd into the valgrind_examples subdirectory.

Valgrind is a tool for finding heap memory access errors and memory leaks in C and C++ programs. Memory access errors are often very difficult bugs to find, and valgrind helps you easily find errors like reads or writes beyond the bounds of a malloc'ed array, accessing free'ed memory, reading uninitialized memory, and memory leaks (not freeing malloc'ed space before all variables referring to it go out of scope).

To use valgrind, just compile with -g, and run valgrind on your program:

make
valgrind ./badprog
The output at first seems a bit cryptic, but once you see the basics of how to interpret it, it is extremely helpful for finding and fixing memory access errors.

My Valgrind Guide has some examples of how to use Valgrind, and contains links to other valgrind resources.


Some more information on debugging tools for C: C programming tools: gdb and valgrind