Skip to content
StudyFame

Debugging C Programs with GDB

Your program compiles, runs and prints the wrong answer. Adding printf everywhere works for small programs, but it is slow and messy. A debugger lets you pause the program at any line, look inside every variable and run it one line at a time, like watching a cricket replay in slow motion.

In this lesson you will learn to use GDB (the GNU Debugger): compile with -g, set breakpoints, step through code, print and watch variables, and use backtrace to find where a program crashed. You will fix a real bug with it.

What You Will Learn

  • What a debugger is and why it beats printf debugging.
  • How to compile a program for debugging.
  • The most important GDB commands.
  • How to find a logic bug with breakpoints, next and print.
  • How to find the line of a crash with backtrace.
  • Tips for debugging in an IDE.

Debugging C Programs with GDB Explained

Exam definition: Debugging is the process of finding and fixing errors (bugs) in a program. A debugger is a tool that runs a program under control so the programmer can stop it at chosen points (breakpoints), execute it statement by statement (stepping) and examine or change variables. GDB is the standard command-line debugger for C on Linux; the program must be compiled with the -g option so that GDB knows the source lines and variable names.

Memory trick: GDB is a TV remote for your program. break = mark the scene, run = play, next = next scene, step = zoom into a scene (enter a function), print = pause and read the subtitles (values), continue = play till the next mark, backtrace = "how did we get here?"

Syntax: Compiling and Starting GDB

gcc -g -O0 program.c -o program    # -g: add debug info, -O0: no optimization
gdb ./program                      # start GDB with the program
gdb --args ./program 10 20         # start GDB and pass command line arguments
(gdb) quit                         # leave GDB
CommandShortWhat it does
break main / break 12bSet a breakpoint at a function or a line
runrStart the program (stops at the first breakpoint)
nextnRun the next line; don't go inside function calls
stepsRun the next line; go inside a function call
continuecRun until the next breakpoint
print sumpShow the value of a variable or expression
display sumShow the value automatically after every step
watch sumStop whenever the variable changes
info localsShow all local variables
listlShow the source code around the current line
backtracebtShow the chain of function calls (where a crash happened)
finishRun until the current function returns; show the return value
deletedRemove breakpoints

Example 1: A Program with a Bug

This program should print the average of four marks, 75. Save it as average.c; the line numbers are used in the GDB session below.

#include <stdio.h>

int average(int a[], int n)
{
    int i;
    int sum = 0;
    for (i = 1; i < n; i++)
        sum += a[i];
    return sum / n;
}

int main(void)
{
    int marks[4] = {70, 80, 90, 60};
    int avg = average(marks, 4);
    printf("Average = %d\n", avg);
    return 0;
}

Output

Average = 57

Code Explanation

  1. (70 + 80 + 90 + 60) / 4 = 300 / 4 = 75, but the program prints 57. There is a logic error: no compile error, no crash, just a wrong answer.
  2. We could stare at the code, but in a big program that doesn't scale. Instead, we pause inside average and look at the values with GDB.
  3. The session below finds two bugs: the loop starts at i = 1, so a[0] (70) is skipped, and sum / n is integer division.

How to Debug It with GDB (Step by Step)

Lines starting with (gdb) are what you type; the rest is GDB's reply. Memory addresses will be different on your computer.

$ gcc -g -O0 average.c -o average
$ gdb ./average
(gdb) break average
Breakpoint 1 at 0x1151: file average.c, line 6.
(gdb) run
Starting program: /home/student/average

Breakpoint 1, average (a=0x7fffffffdf90, n=4) at average.c:6
6           int sum = 0;
(gdb) next
7           for (i = 1; i < n; i++)
(gdb) next
8               sum += a[i];
(gdb) print i
$1 = 1
(gdb) print a[0]
$2 = 70                      <-- a[0] exists, but i started at 1: it is skipped!
(gdb) display sum
1: sum = 0
(gdb) next
7           for (i = 1; i < n; i++)
1: sum = 80
(gdb) next
8               sum += a[i];
1: sum = 80
(gdb) next
7           for (i = 1; i < n; i++)
1: sum = 170
(gdb) finish
Run till exit from #0  average (a=0x7fffffffdf90, n=4) at average.c:7
0x00005555555551b5 in main () at average.c:15
15          int avg = average(marks, 4);
Value returned is $3 = 57    <-- 230 / 4 = 57: integer division also loses .5
(gdb) quit
  • break average pauses as soon as the function starts.
  • next moves one line at a time; display sum shows sum after every step, so you can watch it grow: 0, 80, 170, …
  • print a[0] proves the first mark is never added.
  • finish shows the return value, 57, and reveals the second bug (230 / 4 with integers).

Example 2: The Fixed Program

#include <stdio.h>

double average(const int a[], int n)
{
    int i;
    int sum = 0;
    for (i = 0; i < n; i++)          /* fix 1: start at index 0 */
        sum += a[i];
    return (double)sum / n;          /* fix 2: real division    */
}

int main(void)
{
    int marks[4] = {70, 80, 90, 60};
    double avg = average(marks, 4);
    printf("Average = %.2f\n", avg);
    return 0;
}

Output

Average = 75.00
  • The loop now starts at 0, so all four marks are added: 300.
  • The cast (double)sum makes the division real: 300 / 4 = 75.00.
  • The return type and avg are now double, and printf uses %.2f.

Finding a crash with backtrace

When a program crashes with "Segmentation fault", run it inside GDB. It stops at the crashing line, and backtrace shows how the program got there:

(gdb) run
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555149 in set_first (p=0x0) at crash.c:5
5           *p = 10;
(gdb) backtrace
#0  set_first (p=0x0) at crash.c:5
#1  0x0000555555555171 in main () at crash.c:11
(gdb) print p
$1 = (int *) 0x0             <-- a NULL pointer was dereferenced

Read the backtrace from the top: the crash is in set_first at line 5, which was called from main at line 11 with p = NULL.

Important Points to Remember

  • Compile with -g (and preferably -O0) or GDB can't show lines and variables.
  • break → run → next/step → print is the basic loop.
  • next runs a function call in one go; step goes inside it.
  • display and watch follow a variable automatically.
  • For crashes, run in GDB and use backtrace to find the line and the call chain.
  • IDEs (VS Code, Code::Blocks, CLion) use GDB behind the scenes: clicking in the margin sets a breakpoint.

Common Mistakes Beginners Make

MistakeWhat happensFix
Compiling without -g"No symbol table is loaded"; no line numbersgcc -g prog.c
Debugging an -O2 buildLines jump around, variables "optimized out"Use -O0 while debugging
Typing run before setting breakpointsThe program finishes without stoppingSet break main first
Using step on printfEnters library code with no sourceUse next for library calls, or finish to get out
Forgetting to recompile after a fixGDB shows the old programRecompile, then run again

Debugging with GDB Practice Questions

  1. What is debugging, and what is a debugger?
  2. Why must a program be compiled with -g for GDB?
  3. What is the difference between next and step?
  4. What does backtrace show?
  5. Which command stops the program whenever a variable changes?
Show answers
  1. Debugging is finding and fixing bugs; a debugger is a tool that runs a program under control so you can stop it, step through it and inspect variables.
  2. -g adds debug information (source line numbers, variable and function names) to the executable.
  3. next executes a function call as one step; step enters the called function.
  4. The chain of function calls (the call stack) that led to the current point, e.g. where a crash happened.
  5. watch variable.

Coding Exercise

This factorial program prints 24 for 5! instead of 120. Use GDB (break factorial, display f, display i, next) to find out why, then fix it.

#include <stdio.h>

int factorial(int n)
{
    int f = 1, i;
    for (i = 1; i < n; i++)
        f *= i;
    return f;
}

int main(void)
{
    printf("5! = %d\n", factorial(5));
    return 0;
}
Show solution

Stepping with display i shows the loop stops when i becomes 5, so it multiplies only 1 × 2 × 3 × 4 = 24. The condition must be i <= n.

#include <stdio.h>

int factorial(int n)
{
    int f = 1, i;
    for (i = 1; i <= n; i++)
        f *= i;
    return f;
}

int main(void)
{
    printf("5! = %d\n", factorial(5));
    return 0;
}
5! = 120

Quick Quiz: Debugging with GDB (MCQ)

  1. Which gcc option adds debugging information?

    A) -o   B) -g   C) -c   D) -E

  2. Which GDB command sets a breakpoint?

    A) stop   B) pause   C) break   D) halt

  3. Which command goes inside a function call?

    A) next   B) step   C) finish   D) continue

  4. To see where a segmentation fault happened, use:

    A) print   B) list   C) backtrace   D) delete

  5. p total in GDB:

    A) Pauses the program   B) Prints the value of total   C) Deletes total   D) Sets total to 0

Show answers
  1. B: -g.
  2. C: break.
  3. B: step.
  4. C: backtrace.
  5. B: prints the value of total.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

GDBGNU Debugger for C
Compilegcc -g -O0
break / runSet a breakpoint / start
next vs stepnext skips over calls, step enters them
print / display / watchShow / show every step / stop on change
backtraceCall stack: where a crash happened
finishRun to the end of the function, show the return value

Frequently asked questions

How do you debug a C program with GDB?
Compile with -g, start gdb ./program, set a breakpoint, run, then use next/step and print to inspect values.
What is a breakpoint?
A marked line or function where the debugger pauses the program so you can examine it.
How do you find the cause of a segmentation fault?
Run the program in GDB; when it crashes, type backtrace to see the line and call chain, then print the pointers involved.

Remember

  • GDB = the TV remote: break, run, next, step, print.
  • No -g, no debugging.

Next Topic

Next lesson: Introduction to Data Structures in C. Module 16 begins: you will learn what data structures are and how to choose the right one.