Debugging, sanitizers and safe C
C's speed comes from trusting the programmer: it doesn't check array bounds, null pointers or integer overflow at run time. When something goes wrong, you often get a crash far from the real mistake, or worse, a program that seems to work. Professional C developers rely on tools to catch these bugs early. This lesson covers the toolbox and the habits that make C code safe.
Undefined behaviour
The C standard lists operations whose result is undefined: reading past an array, using freed memory, signed integer overflow, dereferencing NULL, reading an uninitialised variable, and more. "Undefined" doesn't mean "crashes": the compiler is allowed to assume it never happens and optimise accordingly. The same buggy program can work in a debug build and fail in a release build:
#include <stdio.h>
#include <limits.h>
// Tries to detect overflow AFTER it happened: a classic bug.
int add_overflowed(int x, int y) {
int sum = x + y;
return y > 0 && sum < x;
}
int main(void) {
printf("add_overflowed(5, 1) = %d\n", add_overflowed(5, 1));
printf("add_overflowed(INT_MAX, 1) = %d\n", add_overflowed(INT_MAX, 1));
return 0;
}gcc -O0 -o ub ub.c && ./ub
gcc -O2 -o ub ub.c && ./ub-O0: add_overflowed(5, 1) = 0 add_overflowed(INT_MAX, 1) = 1 -O2: add_overflowed(5, 1) = 0 add_overflowed(INT_MAX, 1) = 0
Without optimisation, INT_MAX + 1 wrapped around to a negative number and the check caught it. With -O2, the compiler reasoned: "signed overflow can't happen, so with y > 0, x + y < x is always false", and deleted the check. The overflow still happens; the program just no longer notices. Real security bugs have come from exactly this pattern. The fix is to check before adding (if (y > 0 && x > INT_MAX - y)) or to use C23's ckd_add, and the tools below find the bug.
Layer 1: compiler warnings
Always build with warnings on, and treat them as errors in CI:
gcc -std=c23 -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Werror …#include <stdio.h>
int main(void) {
int count = 10;
double ratio = 2.7;
int scaled = ratio * count; // silently drops the decimals
unsigned int len = 5;
if (scaled > len) printf("bigger\n");
for (int count = 0; count < 2; count++) {} // shadows the outer count
return 0;
}gcc -std=c23 -Wall -Wextra -Wshadow -Wconversion -c warn.cwarn.c:6:18: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion] warn.c:8:16: warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Wsign-compare] warn.c:9:14: warning: declaration of ‘count’ shadows a previous local [-Wshadow]
Each warning is a real bug or a trap waiting to happen. -Wconversion is noisy in older code but very valuable in new code.
Layer 2: sanitizers
Sanitizers add checks to your program at compile time, and stop it with a detailed report at the first bad operation. Use them for every test run:
| Flag | Catches |
|---|---|
-fsanitize=address (ASan) |
Buffer overflows (stack, heap, globals), use after free, double free, memory leaks |
-fsanitize=undefined (UBSan) |
Signed overflow, invalid shifts, null dereference, misaligned pointers, out-of-range conversions… |
-fsanitize=thread (TSan) |
Data races between threads |
gcc -std=c23 -g -fsanitize=undefined -o ub ub.c
./ubadd_overflowed(5, 1) = 0 ub.c:6:9: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int' add_overflowed(INT_MAX, 1) = 1
UBSan pointed at the exact file, line and column, and said what went wrong. Combine them: -fsanitize=address,undefined -g -O1 is a great default for development and test builds. They slow the program down 2–3×, so don't ship them in release builds.
Layer 3: a debugger (GDB)
When a program crashes or misbehaves, a debugger lets you stop it, look at variables, and step through line by line. Compile with -g (debug information) and -O0 (no optimisation, so the code matches your source):
#include <stdio.h>
#include <string.h>
typedef struct { char name[16]; int score; } Player;
int total_score(Player *players, int n) {
int total = 0;
for (int i = 0; i <= n; i++) {
total += players[i].score;
}
return total;
}
int main(void) {
Player team[] = {{"Asha", 30}, {"Ravi", 25}};
Player *nobody = NULL;
printf("first player's score: %d\n", total_score(team, 1)); // expect 30
printf("nobody's score: %d\n", nobody->score);
return 0;
}gcc -std=c23 -g -O0 -o crash crash.c
gdb -q -batch -ex run -ex bt -ex 'info locals' ./crashProgram received signal SIGSEGV, Segmentation fault.
0x... in main () at crash.c:18
18 printf("nobody's score: %d\n", nobody->score);
#0 0x... in main () at crash.c:18
team = {{name = "Asha", '\000' <repeats 11 times>, score = 30}, {name = "Ravi", '\000' <repeats 11 times>, score = 25}}
nobody = 0x0GDB shows exactly where it crashed (crash.c:18), the call stack (bt = backtrace), and the local variables: nobody = 0x0. You'd normally run gdb ./crash interactively:
| Command | Does |
|---|---|
run (r) |
Start the program (run arg1 arg2 with arguments) |
break total_score / break crash.c:9 (b) |
Stop when reaching a function or line |
next (n) / step (s) |
Run one line / step into a function call |
print total (p) |
Show a variable or expression: p players[1], p *ptr |
bt |
Backtrace: how did we get here? |
continue (c) |
Run until the next breakpoint |
watch total |
Stop whenever total changes |
quit (q) |
Leave |
Let's use a breakpoint on the other bug, the off-by-one in total_score:
gdb ./crash
(gdb) break 9
(gdb) run
(gdb) print i
…Breakpoint 1, total_score (players=0x..., n=1) at crash.c:9
$1 = 0
$2 = 1
Breakpoint 1, total_score (players=0x..., n=1) at crash.c:9
$3 = 1
$4 = {name = "Ravi", '\000' <repeats 11 times>, score = 25}We asked for the total of the first n = 1 players and expected 30, but got 55: the loop ran a second time with i = 1 and added Ravi's score, because i <= n should be i < n. Watching i step by step made the logic error obvious. VS Code and CLion give you the same features with a graphical interface on top of GDB or LLDB (lldb is the macOS equivalent).
Core dumps
For crashes on a server, enable core dumps (ulimit -c unlimited). The crashed program's memory is saved to a file, and gdb ./program core opens it exactly as it was at the moment of the crash, even days later.
Layer 4: static analysis
Static analysers read your code without running it and look for bugs across all paths, including ones your tests never execute:
#include <stdlib.h>
#include <stdio.h>
char *load(int fail) {
char *buf = malloc(64);
if (fail) return NULL; // leaks buf on this path
return buf;
}
int main(void) {
char *b = load(0);
free(b);
return 0;
}cppcheck leaky.cleaky.c:6:15: error: Memory leak: buf [memleak]
cppcheck found the leak on a path that main never takes. GCC's built-in -fanalyzer, clang-tidy and Coverity are other popular analysers; each finds bugs the others miss, so it's common to run more than one in CI.
Safe C habits
Tools catch bugs; habits prevent them:
| Instead of | Use | Why |
|---|---|---|
gets, scanf("%s") |
fgets(buf, sizeof buf, stdin) |
They can't limit the input length |
strcpy, strcat, sprintf |
snprintf(dst, size, …) |
Bounded, always terminated |
atoi, atof |
strtol, strtod with error checks |
Detect bad input |
int for sizes and indexes |
size_t |
Never negative, big enough |
a + b on untrusted numbers |
ckd_add(&r, a, b) (C23) |
Detects overflow |
| Ignoring return values | Check every malloc, fopen, fread, write |
Failures are normal events |
| Pointers to freed memory | free(p); p = NULL; |
Turns use-after-free into an obvious crash |
And a few rules for structure:
- Keep functions small and give each resource one clear owner.
- Initialise everything:
int x = 0;,char buf[64] = {0};,Thing t = {0};. - Check inputs at the boundary: validate lengths and ranges where data enters the program.
- Test with sanitizers, fuzz with
-fsanitize=fuzzer(clang's libFuzzer) for code that parses untrusted input.
Where C is going
Memory-safety bugs cause around 70% of serious security vulnerabilities in large C and C++ codebases, according to both Microsoft and Google. That's why new systems code is increasingly written in Rust (now accepted in the Linux kernel), Go or Zig, and why recent C standards keep adding safer tools like ckd_add, nullptr and [[nodiscard]]. C isn't going anywhere: billions of lines of it run the world. Writing it carefully, with these tools, is a valuable skill.
Practice
- Compile every example from the Dynamic memory lesson with
-fsanitize=address,undefinedand read each report. - Put a breakpoint in a loop with GDB,
printa variable each round, and usewatchto stop when it changes. - Add
-Wall -Wextra -Wshadow -Wconversion -Werrorto a Makefile from the previous lesson and fix every warning. - Run
gcc -fanalyzerandcppcheckover an older program of yours.
1.What does "undefined behaviour" mean in C?
2.Which flag catches buffer overflows and use-after-free at run time?
3.What does bt do in GDB?
4.Why compile with -g -O0 for debugging?