Table of Contents

IronForgeCyber

Courses

Resources

Blog

Log In



IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. c-programming
  3. debugging
7 min read

Debugging

C gives you no safety net. A wrong value, a stray pointer, a buffer written one byte too far — the language will happily run all of them and leave you to figure out why the output is wrong or the program crashed. The real skill is finding the cause quickly, and for that you have three tools, each more powerful than the last: printf tracing, GDB, and valgrind. You have seen GDB used throughout this course; here we treat all three as the debugging toolkit they are.

Tracing with printf

The fastest way to see what a program is doing is to make it tell you. Dropping a printf in to show a value, or just to prove a line was reached, solves a surprising number of bugs with zero setup:

c
printf("DEBUG: n=%d, total=%d\n", n, total);

One habit makes this more reliable: print your trace to stderr rather than stdout.

c
fprintf(stderr, "DEBUG: reached the loop, i=%d\n", i);

Stderr is unbuffered, so the message appears immediately — even if the program crashes a line later, which is exactly when a buffered stdout message would be lost before it ever prints. Printf tracing costs you an edit-and-recompile each time and clutters the code, so it is best for quick checks; when you need to poke around without recompiling, reach for GDB.

Using GDB

GDB is an interactive debugger: it runs your program under its control so you can pause it, inspect variables, and step through line by line. A handful of commands cover almost everything:

  • break <place> — pause at a function or line (e.g. break main, break 12).
  • run — start the program; continue resumes after a pause.
  • next — run the next line, stepping over calls; step steps into them.
  • print <expr> (p) — show a variable or expression; backtrace (bt) shows the call stack.
  • finish — run the current function to completion and show what it returns.

Say this program prints the wrong answer — 1 + 2 + 3 + 4 + 5 should be 15, but it reports 10:

buggy.c
1#include <stdio.h>
2
3int sum_to(int n)
4{
5    

We can pin the bug down without a single printf. Break on sum_to, confirm it was called with n = 5, then finish to see what it actually returns:

gdb
$ gcc -g buggy.c -o buggy$ ./buggysum is 10gef➤ set output-radix 10gef➤ break sum_toBreakpoint 1 at 0x1140: file buggy.c, line 5.gef➤ runBreakpoint 1, sum_to (n=5) at buggy.c:5gef➤ p n$1 = 5gef➤ finishValue returned is $2 = 10

sum_to(5) returns 10, so the function is the problem, not the call. From there the loop is the obvious suspect: i < n stops at i = 4 and never adds 5. The fix is i <= n. Compiling with -g is what let GDB show us source lines and variable names — always build with it when debugging.

Catching Memory Bugs with valgrind

printf and GDB are for logic bugs. The nastiest C bugs are memory bugs — leaks, use-after-free, reading uninitialized data, writing past the end of a buffer — and those often cause no visible symptom until much later, somewhere unrelated. valgrind finds them by running your program on a simulated CPU that watches every memory access.

Point it at a program that leaks — a malloc with no matching free — and it tells you exactly how much was lost:

leak.c
1#include <stdlib.h>
2
3int main(void)
4{
5    char 
$ gcc -g leak.c -o leak$ valgrind ./leak== HEAP SUMMARY:==     in use at exit: 100 bytes in 1 blocks== LEAK SUMMARY:==    definitely lost: 100 bytes in 1 blocks== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

definitely lost: 100 bytes — the exact leak. It catches out-of-bounds writes just as precisely. Here a 4-byte buffer is written at index 7, three bytes past its end:

overflow.c
1#include <stdlib.h>
2
3int main(void)
4{
5    char
$ gcc -g overflow.c -o overflow$ valgrind ./overflow== Invalid write of size 1==    at 0x109167: main (overflow.c:6)==  Address 0x4a5d047 is 3 bytes after a block of size 4 alloc'd== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Invalid write of size 1, with the file and line that did it. As with GDB, compile with -g so valgrind can name the exact line.

Useful Flags

valgrind's defaults are deliberately quiet. A handful of flags make it far more informative, and since they are a mouthful to type every time, it is worth saving them in a small wrapper script — mine is called val:

val
1#!/usr/bin/env bash
2
3valgrind \
4    --leak-check=full \
5    --show-leak-kinds=all \
6

The ones that earn their place:

  • --leak-check=full — for every leak, show the full stack of where it was allocated, not just the byte total.
  • --show-leak-kinds=all — report every category: definitely, indirectly, and possibly lost, plus still-reachable blocks.
  • --track-origins=yes — when you use an uninitialized value, trace back to where that memory came from. This turns "somewhere" into an exact line.
  • --track-fds=yes — also report file descriptors still open at exit, the leak's cousin from the file descriptors lesson.
  • --num-callers=40 — deeper backtraces than the default of 12, so you see the whole call chain.

Put that on your PATH and val ./leak runs the full set. Now the leak report points straight at the line that allocated the lost block:

$ val ./leak== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1==    by 0x10914A: main (leak.c:5)== LEAK SUMMARY:==    definitely lost: 100 bytes in 1 blocks== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Same leak as before, but it now names leak.c and the exact allocation site — which is what you actually need to fix it.

Between a printf for a quick look, GDB for stepping through logic, and valgrind for memory errors, you can track down essentially any bug in this course. Time to use all of it — in the practice projects.

int
total
=
0
;
6 for (int i = 1; i < n; i++)
7 total += i;
8 return total;
9}
10
11int main(void)
12{
13 int result = sum_to(5);
14 printf("sum is %d\n", result);
15 return 0;
16}
*
buf
=
malloc
(
100
)
;
6 buf[0] = 'x';
7 return 0; // never freed
8}
*
buf
=
malloc
(
4
)
;
6 buf[7] = 'x'; // past the end of a 4-byte block
7 free(buf);
8 return 0;
9}
--track-origins
=
yes
\
7 --track-fds=yes \
8 --trace-children=yes \
9 --tool=memcheck \
10 --num-callers=40 \
11 --verbose \
12 -s \
13 "$@"