Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Debuggers

Practical and exam-focused notes on debuggers: what they do, key concepts (breakpoints, stepping, symbol info, ptrace), commands to remember, worked gdb examples, common mistakes and exam question types.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Debuggers are the tools engineers use to find and fix bugs in programs while they run or after they crash. In systems programming and device-driver work (and when studying linkers, loaders, symbol tables and debugging info like DWARF), knowing how to use a debugger is essential to inspect program state, follow control flow, and locate incorrect assumptions.

Key ideas

  • Breakpoint — a point (usually a source line or an address) where the debugger forces the program to stop before executing that instruction so you can inspect state. A software breakpoint replaces an instruction with a trap/breakpoint instruction (e.g. int3 on x86, which raises SIGTRAP), and a hardware breakpoint/watchpoint uses CPU debug registers and does not overwrite code. Breakpoints assume single-threaded or thread-aware handling by the debugger.

  • Watchpoint (data breakpoint) — stops execution when a memory variable or address is read or written (depending on the hardware), implemented in hardware (faster, limited count) or by software (slower).

  • Stepping — executing one source line or machine instruction at a time. Two common commands:

    • Step (single-step into): execute one line/instruction, stepping into function calls so you can debug inside called functions. At the machine level this uses the CPU single-step flag (trap on next instruction).
    • Next (step over): execute one source line but do not enter called functions; the debugger runs the called function to completion then stops.
  • Call stack (stack trace) — the chain of active function calls. Each stack frame holds local variables, saved registers and the return address. To draw a call-stack diagram in an answer: draw a vertical stack, label addresses increasing upwards or downwards (state the convention), show top frame (current function) with locals and saved frame pointer (e.g. saved RBP), then the return address, then the caller frame, etc. Label where arguments are (stack or registers) for the calling convention you assume.

  • Frame / Stack frame — the memory and register set associated with one function activation. Define saved frame pointer, return address, local variables.

  • Symbol table — mapping from names (functions, variables) to addresses and types. For source-level debugging you need symbol information compiled into the executable or present in separate debug files.

  • Debug info (DWARF, STABS) — formats that map compiled code back to source: file names, line numbers, variable locations, type information. DWARF is the modern, common format. State the assumption: source-level debugging requires that the program is compiled with debug flags (for GCC: -g) and without optimization or with controlled optimization because heavy optimization moves/optimizes away variables and alters code layout.

  • Core dump — a file capturing the memory image of a crashed process; analysis with a debugger (gdb) plus the binary and symbols lets you inspect the state at crash time. To produce core dumps, ensure resource limit allows them (ulimit -c). A debugger uses core + binary to reconstruct stack trace and variable values where possible.

  • ptrace — the OS interface for debuggers on Unix-like systems. It lets the tracer stop and resume the tracee, inspect and set registers and memory, and catch events like exec, fork and signals. ptrace is the typical kernel mechanism for single-process tracing.

  • Remote debugging — the debugger runs on one machine and the debugged program on another; a small stub on the target uses a protocol (e.g. gdb remote protocol) to communicate. Useful for embedded systems and kernels. Example: on the target run gdbserver :1234 ./prog; on the host run gdb ./prog then (gdb) target remote :1234.

  • Reverse debugging / time-travel debugging — some advanced debuggers record program execution so you can move backwards in time. This trades time and disk for easier root-cause analysis; not all debuggers support it.

Assumptions that commonly appear in exam questions: the tracer and tracee run with appropriate permissions (root or ptrace scope), the program was compiled with -g for source mapping, and optimization is low or disabled to see variables and direct control flow.

If asked to draw, sketch: program text segment (code), data segment (globals), heap (grows up), stack (grows down) and show how breakpoints and watchpoints map: breakpoint at code address, watchpoint at variable's memory address.

Formulas

(Here we list syntax to remember — the 'formulas' of debugging.)

gcc -g -O0 -fno-omit-frame-pointer source.c -o prog — compile with debug info, no optimization, keep frame pointers for clearer stack traces. Alternative for some optimization while preserving debuggability: gcc -g -Og source.c -o prog.

gdb ./prog — start gdb with binary. In gdb, set disable-randomization on disables ASLR so addresses stay stable (useful for address-based breakpoints/diagrams).

break filename:linenumber or b function — set breakpoint at source location or function. Explain: filename:linenumber sets breakpoint at that line in file; b main sets at function entry. Conditional breakpoints: break function if i==42; manage with info break, disable/enable N, delete N, condition N expr, ignore N count.

run [args] or r [args] — start program under debugger.

continue or c — resume execution until next breakpoint or program end.

next or n — step over (source-level). step or s — step into (source-level). finish — run until the current function returns. disassemble shows assembly for the current function; x/10i $pc examines 10 instructions at the current PC; info registers shows CPU registers.

print expression or p expr — evaluate and print variable or expression. info locals — list local variables in current frame.

backtrace or bt — show call stack. frame N or f N — move to frame N. For multithreaded programs: info threads lists threads; thread N selects a thread; thread apply all bt shows backtraces for all threads.

watch var — stop when var is written (or rwatch / awatch for read or access). Note: hardware watchpoints are limited in number.

set var varname = value — change variable in program.

gdb ./prog core — open core dump in gdb.

ulimit -c unlimited — allow core files to be written (shell command).

strace -o trace.txt ./prog — log system calls. ltrace — log library calls.

valgrind --leak-check=full ./prog — memory error and leak detector.

ptrace(request, pid, addr, data) — OS call used by tracers (see verify for exact signature in your system). Request is the action (PTRACE_ATTACH, PTRACE_CONT, etc.).

Worked examples

Example 1 — Finding a NULL-dereference with gdb (step-by-step) Code (segfault.c): 1: #include <stdio.h> 2: int main() { 3: int *p = NULL; 4: printf("%d\n", *p); 5: return 0; 6: }

Steps (numbered):

  1. Compile: gcc -g -O0 segfault.c -o segfault.
  2. Start gdb: gdb ./segfault.
  3. Run: (gdb) run — gdb shows "Program received signal SIGSEGV, Segmentation fault." and stops.
  4. Get stack trace: (gdb) bt prints something like: #0 main () at segfault.c:4
  5. Inspect variables: (gdb) frame 0 then (gdb) print p shows = (int *) 0x0.
  6. Inspect source: (gdb) list shows lines 1-6. You now know dereference of NULL at line 4 caused SIGSEGV. Fix: initialize p or avoid dereference.

Example 2 — Using a watchpoint to catch when a variable changes Code (loop.c): 1: #include <stdio.h> 2: int main() { 3: int i = 0; 4: while (i < 1000000) { 5: if (i % 99999 == 0) ; 6: i++; 7: } 8: printf("done %d\n", i); 9: }

Steps:

  1. gcc -g -O0 loop.c -o loop
  2. gdb ./loop
  3. (gdb) break 4 — stop at start of loop.
  4. (gdb) run — program stops at line 4.
  5. (gdb) watch i — tell gdb to stop on writes to i.
  6. (gdb) continue — when i is next written gdb stops and prints the new value of i and where it changed.
  7. Inspect stack and locals with bt and info locals.

This is useful when the place of mutation is unknown.

Example 3 — Using a core dump and backtrace to find crash origin Code (foo.c): 1: #include <stdio.h> 2: void foo(int n) { int a[2]; a[n] = 10; } 3: int main() { foo(5); return 0; }

Steps:

  1. Allow core files: ulimit -c unlimited (shell).
  2. Compile: gcc -g -O0 foo.c -o foo.
  3. Run ./foo — this code has undefined behavior; it may crash with SIGSEGV and, if enabled, write a core file (core or core.<pid>). If it does not produce a core on your system, run it under gdb directly (gdb ./foo) to capture the crash instead.
  4. Open in gdb: gdb ./foo core.
  5. (gdb) bt shows frame 0: foo at foo.c:2, frame 1: main at foo.c:3.
  6. Inspect arg: (gdb) print n shows = 5. Note: sizeof a returns the size in bytes (typically 8 for int a[2]); get the element count with (gdb) print sizeof a / sizeof a[0] which yields 2. Since n=5 exceeds the array bounds, the write is out of bounds and caused the fault. Fix by checking n or using bounds-safe containers.

In exam answers, show each gdb command, the reason for it, and the critical output (e.g. SIGSEGV at file:line) so the marker can follow your reasoning.

Common mistakes

  • Setting breakpoints in not-yet-loaded shared libraries without enabling pending breakpoints — use set breakpoint pending on or set the breakpoint after the library loads; on true read-only/execute-only code (e.g. ROM/flash in embedded targets), use hardware breakpoints instead of software breakpoints.
  • Expecting watchpoints to work for large arrays without knowing hardware limits — hardware supports only a few watchpoints.
  • Forgetting to set ulimit -c unlimited before testing core dumps.
  • Reading addresses without interpreting calling convention — markers expect you to state which convention you assume when drawing stack/argument placement.

For your exam

Typical question types:

  • Definitions and short notes: define debugger, breakpoint, watchpoint, ptrace, core dump, DWARF.
  • Diagrams: draw program memory layout (text/data/heap/stack) and a call-stack with saved return address and locals; label stack growth direction and offsets.
  • Step-by-step gdb sessions: given C code that crashes, write the gdb commands to find the fault and explain the output.
  • Small programs to trace: show how to set breakpoints, inspect variables, modify variable values to test fixes.
  • Explain ptrace and the sequence of syscalls/events for a tracer.

What a full-marks answer includes:

  • Clear definitions of the terms used (bold in your answer during study).
  • Assumptions stated (compiled with -g, optimization level, OS-specific ptrace behavior).
  • Correct gdb commands and rationale for each step and the important outputs (bt listing, printed variable values, SIG names).
  • Correct, labelled diagrams when requested (stack frame with saved frame pointer, return address, locals).

Quick check

  1. What gdb command shows the call stack?
  2. How do you tell the shell to allow core files?
  3. What is the difference between step and next in a source-level debugger?

Answers: bt (or backtrace); ulimit -c unlimited; step enters called functions, next steps over them.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?