Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

C
C
0/12 completed
Beginner
Hello CVariables and typesOperators and control flowFunctions
Intermediate
Arrays and stringsPointersStructs, enums and unions
Advanced
Dynamic memoryFile I/OThe preprocessor and multi-file programs
Pro
Build tools and MakeDebugging, sanitizers and safe C
Tracks / C / Pro

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:

ub.c
#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;
}
bash
gcc -O0 -o ub ub.c && ./ub
gcc -O2 -o ub ub.c && ./ub
Output
-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 …
warn.c
#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;
}
bash
gcc -std=c23 -Wall -Wextra -Wshadow -Wconversion -c warn.c
Output
warn.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
bash
gcc -std=c23 -g -fsanitize=undefined -o ub ub.c
./ub
Output
add_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):

crash.c
#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;
}
bash
gcc -std=c23 -g -O0 -o crash crash.c
gdb -q -batch -ex run -ex bt -ex 'info locals' ./crash
Output
Program 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 = 0x0

GDB 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:

bash
gdb ./crash
(gdb) break 9
(gdb) run
(gdb) print i
…
Output
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:

leaky.c
#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;
}
bash
cppcheck leaky.c
Output
leaky.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

  1. Compile every example from the Dynamic memory lesson with -fsanitize=address,undefined and read each report.
  2. Put a breakpoint in a loop with GDB, print a variable each round, and use watch to stop when it changes.
  3. Add -Wall -Wextra -Wshadow -Wconversion -Werror to a Makefile from the previous lesson and fix every warning.
  4. Run gcc -fanalyzer and cppcheck over an older program of yours.
✎ Check your understanding

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?

← Build tools and Make