This activity will provide experience using the debugging tool gdb. Perform all of the in-class exercises with your partner.
The basic steps in debugging are:
Debugging
software is challenging,
but keep in mind that all bugs are caused by computers doing exactly
what they
are told; absolutely no mystery in that, and hence all problems are
solvable.
There are many ways people go about debugging, from printing out
messages to
the screen, using a debugger, or just thinking about what the program
is doing
and making an educated guess as to what the problem is. Without a
process to
follow, resolving problems can seem impossible. Most inexperienced
programmers
find themselves in precisely that situation when confronted with a bug. The most troubling thing
is that many
students -- and even commercial coders -- seem to freeze when
unexpected
problems arise. Some literally try making random changes or, worse, try
to run
the program a few more times in hopes that it will start to work again.
The key
to successful debugging is to develop a methodical approach to locating
a
defect, understanding what the cause of the defect is – then applying a
fix. Before applying a fix, a new unit test should be added to the test
suite
that recreates the defect.
With your partner, walk through the following script. The numbered lines explain what is happening. The unnumbered lines are what you should type.
Download the C source file prime.c
and the makefile.
Review the comments in prime.c and examine the makefile. Note the –g compiler option. You must
compile your code with this option in order to run in debug mode with gdb.
make
gdb
prime
h
r
20
bt
Backtrace will typically identify the source line where the error occurred. In the event backtrace does not identify the error, look for other clues - starting with suspicious compiler warnings, as is the case in prime.c at line 44.
q
y
<edit your code>
make
gdb
prime
r
20
b CheckPrime
r
20
n
n
n
p (K % J == 0)
p J
Aha! We are starting our tests of divisibility with 1. Every integer is divisible by 1, so none will be considered prime. We need to change the initialization of J to 2 in line 24. Quit the debugger:
q
y
<edit your code>
make
gdb
prime
r
20
l 26
p J
l CheckPrime
<ENTER>
<ENTER>
q
y
<edit our
code>
make
gdb
prime
r
20