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

  1. 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 in.)

  2. Now enter gdb with the command gdb a.out.

  3. At the gdb prompt, enter run. Run your program as normal. When the program crashes, it will go back to the gdb prompt.

  4. 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 crashed.

  5. Type 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 tutorial or another gdb tutorial.

Via Eclipse

Eclipse helpfully includes a nice GUI interface for debugging. (In fact, it is a front end for gdb).

  1. Under Binaries in your project folder, right-click your executable program (with a bug next to it), select Debug As… > Debug Local C/C++ Application.

  2. Switch to the Debug perspective. Eclipse will probably prompt you about this automatically; but if it does not, you can switch by selecting Open Perspective from the Window menu.

  3. The program does not immediately start executing. To start it executing, click the Resume icon or select Resume from the Run menu.

  4. 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.

  5. You can edit code in this window, but to return to the regular window arranged specifically for editing code, go to Open Perspective in the Window menu and select C/C++.