C for the C++ or Java programmer


A C program contains:

A C program does not contain:

The main function and its input parameters

Variable Declarations

Memory Management

Strings

I/O

File I/O


A sample C file

fact0.c

GDB


Step 1: Compile your program with -g option

g++ -g -o fact1.x fact1.c

Step 2: Start GDB

gdb fact1.x

Step 3: List the suspicious function

(gdb) list computeFact
35 }
36
37 // This function calculates the factorial of n and returns it
38
39 int computeFact(int n)
40 {
41 int accum=0;
42
43 while(n>1) {
44 accum *= n;

Step 4: Set a breakpoint at an appropriate line

(gdb) break 41
Breakpoint 1 at 0x120001938: file fact1.c, line 41.

Step 5: Run the program up to the breakpoint

(gdb) run
Starting program: /a/lamarck.cs.dartmouth.edu/usr/toe/grad/dwagn/cs58/clecture/fact1.x
Enter the value:5
You entered 5


Breakpoint 1, computeFact__Fi (n=5) at fact1.c:41
41 int accum=0;

Step 6: Display the suspicious variable

(gdb) display accum
1: accum = 1

Step 7: Step through the program while monitoring the variable

(gdb) step
43 while(n>1) {
1: accum = 0
(gdb)
44 accum *= n;
1: accum = 0
(gdb)
45 n--;
1: accum = 0
(gdb)
43 while(n>1) {
1: accum = 0
(gdb)
44 accum *= n;
1: accum = 0
(gdb)
45 n--;
1: accum = 0

Step 8: Evaluate the problem and fix it

Change
int accum=0;
to
int accum=1;

The new program, fact2.c runs correctly

Enter the value:5
You entered 5

The factorial of 5 is 120


Webpage maintained by David Wagner dwagn@cs.dartmouth.edu