Debugging C Programs with GDB

When a C program compiles without errors or warnings using gcc but produces incorrect output or crashes (e.g., segmentation fault), the GNU Debugger (gdb) becomes essential for identifying the root cause. Similar to debug modes in IDEs like Keil, gdb alllows setting breakpoints and inspecting variable values during execution to isolate bugs.

Compiling for Debugging

To enable debugging, compile the source with the -g flag:

gcc -g test.c -o ../bin/output

Then launch gdb on the executable. Use the -q (quiet) option to suppress startup messages:

gdb -q ../bin/output

Common GDB Commands

Breakpoint Management

  • Set a breakpoint: Use break (or b) followed by a line number or functon name.

    break 25
    b my_function
    
  • List breakpoints: View all active breakpoints with their details.

    info break
    
  • Delete breakpoints:

    delete 1      # Remove breakpoint with ID 1
    delete        # Remove all breakpoints
    

Inspecting Code and Variables

  • Print variable values:

    print x
    
  • View source code: The list (or l) command displays source lines.

    list          # Show lines around current execution point
    list 10       # Show lines starting at line 10
    list main     # Show code around the 'main' function
    

Program Execusion Control

  • Start execution:

    • run (or r): Start from the beginning or first breakpoint.
    • start: Begin at the start of main, automatically pausing there.
  • Step through code:

    • next (or n): Execute the next line; skip into function calls.
    • step (or s): Step into function calls for detailed inspection.
  • Continue execution:

    continue      # Resume until next breakpoint or program end
    
  • Clear screen (in some environments):

    !clear
    

Passing Command-Line Arguments

If the program expects arguments, they can be supplied in three ways:

  1. At launch:

    gdb --args ../bin/output arg1 arg2
    
  2. Inside GDB before running:

    set args arg1 arg2
    show args
    
  3. During execution:

    run arg1 arg2
    start arg1 arg2
    

Using gdb effectively reveals runtime behavior, helping developers understand control flow, memory state, and logic errors that static analysis cannot catch.

Tags: gdb debugging C GCC command-line

Posted on Fri, 07 Aug 2026 17:00:04 +0000 by Chiaki