CS61C Spring 2011 Lab 4: C and gdb
Goals
This lab will introduce you to the C debugger gdb. You will gain some practical experience using the gdb to debug a buggy C program, and then you’ll write a C program that gdb will be helpful in debugging if you don’t get it right on the first try.
Setup
First copy over the lab harness to a suitable location in your home directory.
$ mkdir ~/lab04
$ cp -R ~cs61c/labs/sp11/04/* ~/lab04/
Exercise 1: Debugger
For this exercise, you will find the GDB reference card useful. Compile hello.c with the "-g" flag:
$ gcc -g -o hello hello.c
This causes gcc to store information in the executable program for gdb to make sense of it. There are two ways to start the debugger:
Single-step through the whole program by:
Type help from within gdb to find out the commands to do these things, or use the reference card.
More gdb commands
Learning these commands will prove useful for the rest of this lab, and your C programming career in general. Create a text file containing answers to the following questions.
Checkoff
Set the breakpoint at main, and show your TA how you run up to that breakpoint.
Show your TA your text document containing the additional gdb commands.
Exercise 2: Debugging a buggy C program
You will now use your newly acquired gdb knowledge to debug a short C program!
Consider the C program ll_equal.c. Compile and run the program, and experiment with it. It will give you the following result:
$ gcc -g -o ll_equal ll_equal.c
$ ./ll_equal
equal test 1 result = 1
Segmentation fault
Now, start gdb on the program, following the instructions in exercise 1. Set a breakpoint in the ll_equal function, and run the program. When the debugger returns at the breakpoint, step through the instructions in the function line by line, and examine the values of the variables. Pay attention to the pointers a and b in the function. Are they always pointed to the right address? Find the bug and fix it.
Checkoff
Explain the bug and your fix to the function.
Exercise 3: Pointers and Structures in C
Here's one to help you in your interviews. In ll_cycle.c, complete the function ll_has_cycle to implement the following algorithm for checking if a singly-linked list has a cycle.
After you have correctly implemented ll_has_cycle, the program you get when you compile ll_cycle.c will tell you that ll_has_cycle agrees with what the program expected it to output.
Checkoff
Show your ll_has_cycle function to the TA.