CodeBlanks Logo Icon CodeBlanks

gdb basics

  • C course
  • Intermediate
  • Lesson 94/116
  • 5 min

Learn to debug programs with gdb.

gdb basics

gdb (GNU Debugger) runs C programs step by step and lets you inspect their internal state. To use it, compile with -g: gcc -g program.c -o program.

Then start with gdb ./program. Key commands: run starts the program, quit leaves gdb, list shows source. Even if the program crashes, gdb stays active so you can see where it stopped. This is much faster than adding printf; you can inspect variables on the spot, pause and resume execution at will.

A debuggable program

For gdb to be useful, the program should have several functions. Each function is an anchor point where you can pause in gdb. A simple example: int sum_range(int lo, int hi) sums the integers in a range.

Implementation: int total = 0; for (int i = lo; i <= hi; i++) total += i; return total;. main calls this function and prints the result. In gdb you can break sum_range to pause at the function entry and inspect variables one by one. This structure is the basis for testing each function independently in real projects.

Practice Write a debuggable program

Write int sum_range(int lo, int hi) that sums from lo to hi. In main, print the result with printf("%d\n", sum_range(1, 10));.

Starter code

main.c
#include <stdio.h>

// Write the sum_range function
// Call sum_range(1, 10) in main and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int sum_range(int lo, int hi) {
    int total = 0;
    for (int i = lo; i <= hi; i++) {
        total += i;
    }
    return total;
}

int main(void) {
    printf("%d\n", sum_range(1, 10));
    return 0;
}

Expected output

55

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How do you compile a program for gdb debugging?

  • gcc -s program.c -o program
  • gcc -O2 program.c -o program
  • gcc -g program.c -o program Correct answer
  • gcc -c program.c

Explanation: The -g flag adds debug info; gdb uses it.

2 Complete the sum_range call

Question
printf("%d
", sum_range(1, ____));
Answer
printf("%d
", sum_range(1, 10));

Explanation: sum_range(1, 10) sums 1 through 10; the result is 55.

3 Match the gdb commands

Term Meaning
run Start program
quit Leave gdb
list Show source
-g Debug info

All lessons in Intermediate