Debugging C programs
There is some chance that your program will run into a segmentation
fault, memory protection error, or some other abnormal crashing
behavior. A debugger is a program that helps to
identify where such crashes occur.
Via the command line
To compile the program, use:
gcc -g -Wall *.c.
(The -g option is important: It tells gcc to
include debugging information in a.out, which
gdb will use to know which line the program is
Now enter gdb with the command
At the gdb prompt, enter
Run your program as normal. When the program crashes, it will go
back to the gdb prompt.
You can enter
where, and gdb will
show the current stack of subroutine calls, and the line number
for each. This will indicate the line where the program
quit to exit gdb and return to
the shell prompt.
The gdb utility is capable of doing much more, too:
You can set breakpoints, step through the program line by line,
and probe the values of variables as the
program runs. For more information about how to use it, read a gdb
Eclipse helpfully includes a nice GUI interface for debugging.
(In fact, it is a front end for gdb).
Under Binaries in your project folder, right-click your
executable program (with a bug next to it), select
Debug As… > Debug Local C/C++
Switch to the Debug perspective. Eclipse will probably prompt
you about this automatically; but if it does not, you can switch by
Open Perspective from the Window menu.
The program does not immediately start executing. To start
it executing, click the
or select Resume from
the Run menu.
Run the program as normal. When the program crashes, the
Debug view will display the call stack at that point. You can
click on any function call in the stack, and Eclipse will show
you the code being executed if it can. Also, the Variables view will
display values for local variables.
You can edit code in this window, but to return to the regular
window arranged specifically for editing code, go to
Perspective in the Window menu and select C/C++.