SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 54
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 54 of 90

Secure coding in C and C++

bounds checkinggets vs fgetsstrcpy vs strncpy/strlcpysprintf vs snprintfsize_t and checked arithmeticcompiler warnings (-Wall -Wextra -Werror)_FORTIFY_SOURCEsanitizers (ASan, UBSan, MSan, TSan)Valgrindstatic analysisfuzzing introduction (libFuzzer, AFL++ concept)C++ RAIIsmart pointersstd::span

These are the notes for Cybersecurity Fundamentals (defensive), episode 54. Episode 53 met the memory-corruption bug classes: buffer overflows, use-after-free, integer and format-string bugs, Heartbleed. This episode shows the fixes: the functions, flags and tools that stop each one, in C and C++. Everything here is free and built into the compilers you already use. Every term is defined the first time it appears; the Glossary collects them.

Scope. Everything is defensive and runs on our own toy buffers; no real system is touched and no working exploit is shown. Samples were run on 12 Nov 2026: live runs in the SyntaxPilot compiler (gcc 13.3 -O2 with _FORTIFY_SOURCE on, g++ -std=c++17); the sanitizer, Valgrind and -Wall reports were produced separately with gcc. Addresses differ every run.

The six habits

Habit Fixes (from episode 53)
Safe input and strings: fgets, snprintf, strlcpy buffer overflow
size_t and checked arithmetic integer overflow leading to overflow
Compiler warnings: -Wall -Wextra -Werror typos, bad casts, signedness bugs
_FORTIFY_SOURCE overflows that slip through review
Sanitizers and Valgrind all memory bugs, during testing
C++ RAII, smart pointers, containers use-after-free, leaks, OOB access

Problem 1: safe input and strings

Real-life example: pouring water with no limit spills on the floor; a funnel that stops at the brim never overflows. The old C functions gets, strcpy, sprintf and strcat copy text without knowing the size of the target; the safe versions take a size and refuse to write past it.

  • A buffer (episode 52) is a block of memory, e.g. char name[16].
  • gets(buf) reads a whole line with no size limit, so a long line overflows. It is so dangerous it was removed from the C language in C11 (SEI CERT C rule STR31-C: gets "is inherently unsafe and should never be used"; it was "deprecated in C99 Technical Corrigendum 3 and removed from C11").
  • fgets(buf, size, stream) reads at most size - 1 characters and always ends the string with \0.

Demo 1: fgets instead of gets

// Reading a name into a 16-byte box, safely.
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[16];                       // room for 15 chars + '\0'
    // gets(name) was REMOVED from C11: it can't limit how much it reads,
    // so a long line overflows name. fgets takes the size, so it can't.
    if (fgets(name, sizeof name, stdin)) {
        name[strcspn(name, "\n")] = '\0';     // trim the newline
        printf("input was long, but we stored only %zu chars: %s\n",
               strlen(name), name);
    }
    return 0;
}

Fed a long line, real output:

input was long, but we stored only 15 chars: Ravi Kumar from

fgets stored only 15 characters because it was told the box size. (On Linux, getline is another option: it grows the buffer instead of truncating.)

  • sprintf(buf, ...) formats with no size; snprintf(buf, size, ...) writes at most size - 1 characters, always \0-terminates, and returns how many it wanted to write (so you can detect truncation).

Demo 2: snprintf instead of sprintf

// Build a label from two names into a 16-char box.
#include <stdio.h>
#include <string.h>

int main(void) {
    char label[16];
    const char *first = "Venkataraman";   // 12 chars
    const char *last  = "Iyer";           // 4 chars -> "Venkataraman Iyer" = 17

    // snprintf writes AT MOST size-1 chars and always ends with '\0'.
    int need = snprintf(label, sizeof label, "%s %s", first, last);
    printf("label: \"%s\"\n", label);
    printf("snprintf wanted %d chars; box holds %zu, so it truncated.\n",
           need, sizeof label - 1);
    return 0;
}

Real output:

main.c: In function 'main':
main.c:11:50: warning: '%s' directive output truncated writing 4 bytes into a region of size 3 [-Wformat-truncation=]
    8 |     const char *last  = "Iyer";           // 4 chars -> "Venkataraman Iyer" = 17
      |                         ~~~~~~                    
......
   11 |     int need = snprintf(label, sizeof label, "%s %s", first, last);
      |                                                  ^~
In file included from /usr/include/stdio.h:980,
                 from main.c:2:
In function 'snprintf',
    inlined from 'main' at main.c:11:16:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:54:10: note: '__builtin___snprintf_chk' output 18 bytes into a destination of size 16
   54 |   return __builtin___snprintf_chk (__s, __n, __USE_FORTIFY_LEVEL - 1,
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   55 |                                    __glibc_objsize (__s), __fmt,
      |                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   56 |                                    __va_arg_pack ());
      |                                    ~~~~~~~~~~~~~~~~~
label: "Venkataraman Iy"
snprintf wanted 17 chars; box holds 15, so it truncated.

The two names needed 17 characters but the box holds 15, so snprintf truncated safely and reported that it wanted 17; the compiler even warned about the truncation at build time. Truncation loses data but never corrupts memory, and you can check the return value and react.

The swap list

Dangerous (no size) Safe (takes a size)
gets(buf) fgets(buf, sizeof buf, stdin)
strcpy(d, s) snprintf / strlcpy(d, s, size)
sprintf(d, ...) snprintf(d, sizeof d, ...)
strcat(d, s) strlcat(d, s, size) / snprintf

strlcpy and strlcat (from OpenBSD) were added to glibc in version 2.38 (2023). The single rule: never copy or format into a buffer without passing the buffer's size. If a function doesn't take a size, don't use it.

Problem 2: checked arithmetic

  • Use size_t (the unsigned type for sizes) for lengths and counts.
  • An integer overflow (episode 53) wraps a too-big number. The classic case is n * size for an allocation: if the product is too big for size_t, it wraps to a small number, and you allocate far too little, then overflow it.

Demo 3: a checked multiply

// Total bytes for n records of 'size' each. n and size come from outside.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int alloc_v1(size_t n, size_t size) {       // n * size can overflow
    size_t bytes = n * size;                 // may wrap to a small number!
    printf("  v1: n=%zu size=%zu -> bytes=%zu\n", n, size, bytes);
    return bytes != 0;
}

int alloc_v2(size_t n, size_t size) {        // checked multiply
    if (size != 0 && n > SIZE_MAX / size) {
        printf("  v2: n=%zu size=%zu -> refused (would overflow)\n", n, size);
        return 0;
    }
    printf("  v2: n=%zu size=%zu -> bytes=%zu OK\n", n, size, n * size);
    return 1;
}

int main(void) {
    size_t n = (SIZE_MAX / 8) + 2, size = 8;  // n*size wraps around
    alloc_v1(n, size);
    alloc_v2(n, size);
    alloc_v2(1000, 8);
    return 0;
}

Real output:

  v1: n=2305843009213693953 size=8 -> bytes=8
  v2: n=2305843009213693953 size=8 -> refused (would overflow)
  v2: n=1000 size=8 -> bytes=8000 OK

alloc_v1's multiply wrapped a giant n * 8 down to 8 bytes; trusting that would overflow instantly. alloc_v2 checks n > SIZE_MAX / size before multiplying and refuses. (GCC/Clang also provide __builtin_mul_overflow(a, b, &out), which returns whether the multiply overflowed.) Many overflows start with one unchecked size calculation.

Problem 3: the compiler as a bug finder

The compiler reads every line, so it often already sees the bug, but by default it stays quiet. Three flags change that:

  • -Wall -Wextra turn on a large set of warnings.
  • -Werror turns every warning into an error, so the build fails until the code is fixed.

Demo 4: -Wall -Wextra -Werror

$ gcc -Wall -Wextra -Werror app.c -o app
app.c:5:9: error: suggest parentheses around assignment
            used as truth value [-Werror=parentheses]
    5 |     if (count = 3)       // '=' instead of '=='
app.c:7:15: error: comparison of integer expressions of
            different signedness: 'int' and 'unsigned int'
            [-Werror=sign-compare]
cc1: all warnings being treated as errors
$ echo $?
1

It caught an = written where == was meant (assignment used as a truth value) and a signed-vs-unsigned comparison (the kind that let a negative length through last episode), and -Werror made the build fail (exit code 1). Turn these on from day one; a warning is a free bug report.

Problem 4: _FORTIFY_SOURCE

_FORTIFY_SOURCE is a compiler feature (on by default in the SyntaxPilot stage) that, when it can tell a buffer's size, adds a runtime size check to functions like strcpy, memcpy and sprintf, stopping the program if a copy would overflow.

Demo 5: an overflow caught at run time

// _FORTIFY_SOURCE (on by default here) adds a runtime size check to strcpy.
#include <stdio.h>
#include <string.h>

int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0);
    char token[16];
    const char *name = "Ravi";
    strcpy(token, name);                 // fits
    printf("ok: %s\n", token);

    const char *attack = "AAAAAAAAAAAAAAAAAAAA";   // 20 chars
    strcpy(token, attack);               // overflow -> FORTIFY stops it
    printf("this line never runs\n");
    return 0;
}

Real output:

In file included from /usr/include/string.h:548,
                 from main.c:3:
In function 'strcpy',
    inlined from 'main' at main.c:13:5:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:79:10: warning: '__builtin___memcpy_chk' writing 21 bytes into a region of size 16 overflows the destination [-Wstringop-overflow=]
   79 |   return __builtin___strcpy_chk (__dest, __src, __glibc_objsize (__dest));
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ok: Ravi

*** buffer overflow detected ***: terminated

The 20-into-16 copy was caught at run time (*** buffer overflow detected ***: terminated) before any damage, and the next line never ran. Turn it on with -D_FORTIFY_SOURCE=2 and optimisation enabled. It is nearly free, but it is a safety net, not a replacement for writing safe code (it only guards calls where the size is known).

Problem 5: sanitizers, Valgrind, static analysis and fuzzing

A sanitizer is a build mode where the compiler adds checks to your program so that, when you run your tests, hidden bugs are caught with the exact line. You use them during testing, not in the shipped build, because they slow the program down (AddressSanitizer about 2×, per the LLVM docs).

Tool Flag Catches
AddressSanitizer (ASan) -fsanitize=address out-of-bounds (heap/stack/globals), use-after-free, double free, leaks
UndefinedBehaviorSanitizer (UBSan) -fsanitize=undefined signed overflow, OOB index, bad shifts, misaligned access
MemorySanitizer (MSan) -fsanitize=memory reads of uninitialised memory
ThreadSanitizer (TSan) -fsanitize=thread data races between threads
Valgrind (Memcheck) run under valgrind leaks, invalid reads/writes, uninitialised use

ASan report (the overflow from episode 53)

$ gcc -fsanitize=address app.c -o app && ./app
==ERROR: AddressSanitizer: stack-buffer-overflow
WRITE of size 20 at 0x7f57d3d00070 thread T0
    #0 save_name app.c:7   (in strcpy)
  [32, 48) 'token' (line 6)
     <== Memory access at offset 48 overflows this variable
SUMMARY: AddressSanitizer: stack-buffer-overflow in strcpy

It names the bug, the size of the bad write, the exact line and the variable. Add -O1 and -fno-omit-frame-pointer for clean reports.

UBSan report

$ gcc -fsanitize=undefined app.c -o app && ./app
app.c:5:25: runtime error: index 4 out of bounds
            for type 'int [4]'
app.c:7:5:  runtime error: signed integer overflow:
            2147483647 + 1 cannot be represented in type 'int'

Each undefined-behaviour event is reported with its line and the numbers involved.

Valgrind report

$ valgrind --leak-check=full ./app
==  HEAP SUMMARY:
==    in use at exit: 3,200 bytes in 100 blocks
==  3,200 bytes in 100 blocks are definitely lost
==  LEAK SUMMARY:
==     definitely lost: 3,200 bytes in 100 blocks
==  ERROR SUMMARY: 1 errors from 1 contexts

Valgrind watched every allocation and found 100 blocks (3,200 bytes) definitely lost: a leak, with the allocating line.

Static analysis reads your code without running it and flags risky patterns (free tools: scan-build/Clang Static Analyzer, clang-tidy, cppcheck). Fuzzing throws millions of random or mutated inputs at your program to find the one that crashes (tools: libFuzzer, AFL++). Both find bugs before an attacker does; we only name them here.

Problem 6: C++ that's safe by default

Modern C++ removes whole bug classes by design.

  • RAII (Resource Acquisition Is Initialisation) means the object that owns a resource frees it automatically when it goes out of scope, so there is no free/delete to forget.
  • A smart pointer is RAII for heap memory: std::unique_ptr owns one object and frees it automatically; std::make_unique<T>(...) creates one. No leak, no use-after-free.
  • Containers know their own size: std::vector and std::string replace raw arrays and char*. vector::at(i) checks the index and throws std::out_of_range instead of corrupting memory (operator[] does not check, so prefer at at trust boundaries).
  • std::span (C++20) is a lightweight view that carries a pointer and its size together, so length always travels with the data.

Demo 6: RAII, smart pointers and at()

// C++ gives you safety by default. Three tools.
#include <iostream>
#include <vector>
#include <memory>
#include <string>

int main() {
    // 1. RAII + smart pointer: memory frees itself, no free() to forget.
    auto order = std::make_unique<std::string>("2 chai mugs");
    std::cout << "order: " << *order << "\n";
    // when 'order' goes out of scope, the memory is freed automatically.

    // 2. std::vector knows its own size; .at() checks the index.
    std::vector<int> marks = {90, 85, 77, 68};
    std::cout << "marks.at(2) = " << marks.at(2) << "\n";
    try {
        std::cout << marks.at(4) << "\n";    // index 4 of 4: checked!
    } catch (const std::out_of_range& e) {
        std::cout << "marks.at(4) threw: " << e.what() << "\n";
    }
    return 0;
}

Real output:

order: 2 chai mugs
marks.at(2) = 77
marks.at(4) threw: vector::_M_range_check: __n (which is 4) >= this->size() (which is 4)

order freed itself (RAII) with no delete. marks.at(4) on a 4-element vector did not corrupt memory: it threw an exception we caught. In plain C that same access silently read past the array (episode 52). Three C++ habits: use vector/string instead of raw arrays and char*, use smart pointers instead of new/delete, and use at() or std::span so length travels with the data.

The layered defence (defence in depth)

No single tool catches everything, so you layer them (episode 3):

Stage Tools
Write safe functions, size_t, checked math, C++ containers and smart pointers
Compile -Wall -Wextra -Werror, -D_FORTIFY_SOURCE=2
Test ASan, UBSan, MSan, TSan, Valgrind, fuzzing
Review static analysis, code review, SEI CERT C rules

The SEI CERT C Coding Standard (Carnegie Mellon SEI) is a numbered rulebook for safe C (e.g. STR31-C on string space, which forbids gets). Each layer catches what the last one missed.

The whole chain

  1. Overflow → fgets, snprintf, strlcpy (pass the size).
  2. Size wrap → size_t + checked multiply.
  3. Typos and bad casts → -Wall -Wextra -Werror.
  4. A copy too big → _FORTIFY_SOURCE catches it at run time.
  5. Hidden bugs → ASan, UBSan, Valgrind, fuzzing.
  6. Manual memory → RAII, smart pointers, at(), span.

Common mistakes (and the fix)

Unsafe Problem Fix
gets(buf); removed from C11; no size limit fgets(buf, sizeof buf, stdin)
sprintf(buf, "%s", name); overflows on a long name snprintf(buf, sizeof buf, ...)
strcpy(d, s); no destination size snprintf / strlcpy(d, s, size)
size_t b = n * size; the multiply can wrap check n > SIZE_MAX / size first
new int[4]; ... delete[] leak if you forget delete std::vector / std::unique_ptr
vec[i] at a trust boundary no bounds check vec.at(i)
building with no warning flags bugs ship silently -Wall -Wextra -Werror

Mini project: harden a toy program

Take a small C program that uses gets, strcpy, a raw n * size allocation and vec[i], and:

  1. Replace every unsafe function with a size-taking one.
  2. Add a checked multiply before the allocation.
  3. Build it with -Wall -Wextra -Werror and fix every warning.
  4. Run it under -fsanitize=address and -fsanitize=undefined and confirm no reports.
  5. Rewrite it in C++ with std::string, std::vector and std::unique_ptr.

Practice

1. Rewrite a gets/strcpy toy with fgets/snprintf.

Solution
char name[16];
if (fgets(name, sizeof name, stdin)) {
    name[strcspn(name, "\n")] = '\0';
    char label[32];
    snprintf(label, sizeof label, "User: %s", name);
    printf("%s\n", label);
}

Both calls take a size, so neither can overflow.

2. Add a checked multiply to an allocation.

Solution
if (size != 0 && n > SIZE_MAX / size) return NULL;   // would overflow
void *p = malloc(n * size);                          // now safe

Or if (__builtin_mul_overflow(n, size, &bytes)) return NULL;

3. What does -Werror add on top of -Wall -Wextra?

Answer

-Wall -Wextra only warn; the build still succeeds, so warnings are easy to ignore. -Werror turns every warning into an error, so the build fails until they are fixed, which stops the bug from ever shipping.

4. Why run sanitizers during testing, not in production?

Answer

They slow the program down (ASan about 2×) and increase memory use, so they are for catching bugs while you test, not for shipping. The shipped build uses _FORTIFY_SOURCE and system mitigations (episode 55) instead.

Quick quiz

char name[16];
// A: gets(name);
// B: strcpy(name, input);
// C: sprintf(name, "%s", input);
// D: snprintf(name, sizeof name, "%s", input);
// input is attacker-controlled and may be long

Which line is safe?

Answer

D. Only snprintf takes the destination size (sizeof name) and never writes past it. gets has no limit (and is removed from C11); strcpy and sprintf don't know name's size, so a long input overflows.

Interview questions

  1. Why is gets banned, and what replaces it? It cannot limit how much it reads, so any long line overflows; it was removed in C11. Use fgets (or getline on POSIX).
  2. How does snprintf make sprintf safe? It takes the destination size, never writes past size - 1, always \0-terminates, and returns the length it wanted (so you can detect truncation).
  3. How can an integer overflow cause a heap overflow? n * size for an allocation can wrap to a small number, so you allocate too little and then write past it. Fix: check n > SIZE_MAX / size or use a checked-multiply builtin.
  4. What do -Wall -Wextra -Werror and _FORTIFY_SOURCE each do? The flags turn warnings on and make them build errors (compile-time); _FORTIFY_SOURCE adds runtime size checks to known-size buffer calls.
  5. Name the main sanitizers and what each finds. ASan (memory errors, leaks), UBSan (undefined behaviour), MSan (uninitialised reads), TSan (data races); plus Valgrind for leaks and invalid memory use.
  6. What is RAII and how do smart pointers use it? RAII ties a resource's lifetime to an object's scope, so cleanup is automatic; std::unique_ptr/shared_ptr free heap memory when they go out of scope, preventing leaks and use-after-free.
  7. Why prefer std::vector/at()/std::span over raw arrays and pointers? They carry their size, bounds-check (at), and manage memory, so overflows and dangling pointers become impossible or caught.

Glossary

Term Meaning
buffer a block of memory, e.g. char name[16]
gets reads a line with no size limit; removed from C11
fgets reads at most size-1 chars; safe
sprintf / snprintf format into a buffer; snprintf takes a size and truncates safely
strcpy / strlcpy copy a string; strlcpy takes a size (added to glibc 2.38)
size_t the unsigned type for sizes and lengths
checked arithmetic testing a multiply/add for overflow before doing it
__builtin_mul_overflow a GCC/Clang checked multiply
-Wall -Wextra turn on compiler warnings
-Werror turn warnings into build errors
_FORTIFY_SOURCE compiler feature adding runtime size checks to known-size calls
sanitizer a build mode that adds runtime checks to catch bugs during testing
AddressSanitizer (ASan) -fsanitize=address: overflows, use-after-free, leaks
UBSan -fsanitize=undefined: undefined behaviour
MSan -fsanitize=memory: uninitialised reads
TSan -fsanitize=thread: data races
Valgrind (Memcheck) a tool that finds leaks and invalid memory use
static analysis reading code without running it to flag risky patterns
fuzzing feeding random/mutated inputs to find crashes (libFuzzer, AFL++)
RAII the owning object frees its resource when it goes out of scope
smart pointer RAII for heap memory (std::unique_ptr, std::shared_ptr)
std::vector / std::string containers that know their size; replace raw arrays/char*
.at(i) a bounds-checked index that throws instead of corrupting
std::span a view carrying a pointer and its size together (C++20)
SEI CERT C a numbered coding standard for safe C
defence in depth layering independent protections (episode 3)

Summary

Secure C and C++ is a stack of cheap habits: swap size-less functions (gets, strcpy, sprintf) for size-taking ones (fgets, snprintf, strlcpy); use size_t and check your arithmetic; build with -Wall -Wextra -Werror and _FORTIFY_SOURCE; run ASan, UBSan, Valgrind and fuzzing while you test; use static analysis and SEI CERT C in review; and in C++ let RAII, smart pointers, vector::at and std::span make whole bug classes impossible. No single layer is enough; together they catch almost everything. Next episode: the mitigations the system itself adds, stack canaries, DEP/NX, ASLR, and the memory-safe languages like Rust that stop these bugs by design.