Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 171 ยท Errors and Debugging

Secure C++ Coding

Write safer C++ by avoiding dangling references, check bounds with at() and span, validate integer sizes, enable hardened library modes and compiler hardening flags.

Many of the worst security bugs in history, from buffer overflows to use-after-free exploits, come from a small group of C++ mistakes: reading or writing outside an array, using an object after it died, and doing arithmetic on sizes that quietly wrapped around. None of them need clever attackers to cause harm. They only need input your program didn't expect. The good news is that modern C++ gives you the tools to remove most of these bugs by design, and your compiler can add safety nets for the rest.

This lesson is a practical checklist. You'll see the three big classes of memory errors (lifetime, bounds and integer size), the C++ types that make them harder to write, how to turn on checks in the standard library, and which compiler flags harden a release build. It builds on Undefined Behavior and Memory Safety, Destructors and RAII, std::span and Debugging.

Why "it works on my machine" is not enough

Memory-safety bugs are undefined behavior, so a test run that passes proves nothing. The same code may crash on another compiler, behave differently after an unrelated edit, or hand an attacker control of the program. Security work therefore has three layers:

flowchart TD
    A["1. Write code that cannot<br/>express the bug<br/>(RAII, span, string, vector)"] --> B["2. Add checks where the<br/>language cannot help<br/>(at, hardened library, validation)"]
    B --> C["3. Catch what slipped through<br/>(warnings, sanitizers,<br/>hardening flags, fuzzing)"]

Prevent first, check second, detect third. Each layer catches mistakes that the layer above missed.

Lifetimes: never outlive the object

A reference, pointer, std::string_view or std::span does not own its data. If the owner dies first, the view dangles, and using it is undefined behavior. The compiler catches only the simplest cases.

C++
std::string_view name() {
    std::string s = "temporary";
    return s;                 // the string dies here; the view dangles
}

const std::string& first_word(const std::string& line);
const auto& w = first_word(std::string{"hello world"});   // binds to a dead temporary

Rules that prevent most lifetime bugs:

  • Return owning types (std::string, std::vector, std::unique_ptr) from functions; take views as parameters only.
  • Never store a string_view, span or iterator in a long-lived object unless you can point to what keeps the owner alive.
  • Don't keep iterators or references into a std::vector across push_back, insert or erase: they may be invalidated.
  • Don't capture locals by reference ([&]) in a lambda that outlives the function, for example one handed to a thread or stored for later.
  • Own heap memory with std::unique_ptr or std::shared_ptr, never with a raw new/delete pair (see unique_ptr and shared_ptr).
C++ A safe alternative to a dangling view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The temporary created by make_label(12345) lives until the end of the full expression, so passing it to a function that takes a string_view is fine. Storing the view and using it on a later line is the bug.

Bounds safety: check the index

operator[] on std::vector, std::array, std::string and C arrays does no checking at all. An out-of-bounds read can leak secrets from nearby memory (that is how Heartbleed worked); an out-of-bounds write can overwrite a return address. Prefer these options:

  • Range-for loops and algorithms never need an index: for (int x : v), std::ranges::sort(v).
  • at(i) checks the index and throws std::out_of_range. Use it where the index comes from outside the program.
  • std::span carries a pointer and a length together, replacing the (T*, size_t) pair that is so easy to mismatch.
  • std::string and std::vector replace char buf[256] and strcpy/sprintf. Avoid the C string functions strcpy, strcat, sprintf and gets completely.
C++ Checked access with at() and span

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Checked access has a small cost, so inside a hot loop whose bounds you have already proven (for instance for (std::size_t i = 0; i < v.size(); ++i)) plain [] is fine. The rule of thumb: check at the boundary, trust inside it. Validate everything that comes from files, sockets, command lines or users before it becomes an index.

Integer sizes: wrap-around is a vulnerability

A famous bug pattern is allocating count * size bytes, where the multiplication overflowed and produced a small number, and then writing count elements into the tiny buffer. Unsigned arithmetic wraps silently; signed overflow is undefined behavior. Both are dangerous when the numbers come from outside.

Habits that help:

  • Check before you compute: if (count > max / size) { reject; }.
  • Use std::in_range<T>(value) (C++20, in <utility>) to test whether a value fits the target type without a sign-comparison trap.
  • Use the right type for sizes (std::size_t) and avoid mixing signed and unsigned in comparisons; the compiler warning -Wsign-compare points at them.
  • Turn narrowing into an error with brace initialization: int n{big}; does not compile for a long.
C++ Validating a size from outside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The plain comparison -1 < 5u makes GCC print a -Wsign-compare warning and prints false, because -1 is converted to the unsigned value 4294967295. std::cmp_less compares mathematically and gives true. That mismatch is behind many real "negative length" vulnerabilities.

Standard library hardening

Even careful code has bugs, so the standard libraries let you turn operator[], front(), back(), std::span access and similar calls into checked operations that abort the program on misuse. A controlled crash is far better than silent memory corruption, because it stops an attack and gives you a stack trace.

  • libstdc++ (GCC): define _GLIBCXX_ASSERTIONS (compile flag -D_GLIBCXX_ASSERTIONS). It is cheap enough for many production builds.
  • libc++ (Clang): define _LIBCPP_HARDENING_MODE as _LIBCPP_HARDENING_MODE_FAST, _EXTENSIVE or _DEBUG. The fast mode is designed for production.
  • MSVC: debug builds check iterators; _ITERATOR_DEBUG_LEVEL controls the level.
  • C++26 contracts and hardened implementations are standardizing this idea, so checked library calls become portable.

You normally set these in the build system, but a macro defined before the first #include works for a demonstration. The program below deliberately aborts:

C++ Hardened operator[] stops an overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first line prints and the second access stops the program with an assertion message (__n < this->size()), ending in a SIGABRT. Without the macro the same code would simply read whatever sits after the vector's buffer.

Compiler and linker hardening

Hardening flags make exploits harder even when a bug exists. A typical GCC or Clang release line looks like this:

Terminal
g++ -std=c++23 -O2 -Wall -Wextra -Wconversion -Wformat=2 \
    -D_GLIBCXX_ASSERTIONS -D_FORTIFY_SOURCE=3 \
    -fstack-protector-strong -fstack-clash-protection -fcf-protection \
    -fPIE -pie -Wl,-z,relro,-z,now \
    main.cpp -o app
Flag What it does
-Wall -Wextra -Wconversion Warnings for suspicious code, including silent narrowing; treat them as errors in CI (-Werror)
-D_FORTIFY_SOURCE=3 Checks buffer sizes in C library calls such as memcpy (needs optimization)
-fstack-protector-strong Places a canary before return addresses; a smashed stack aborts the program
-fstack-clash-protection Probes large stack allocations so they cannot jump over the guard page
-fcf-protection Control-flow enforcement on supporting CPUs (x86)
-fPIE -pie Position-independent executable, so ASLR can randomize the code address
-Wl,-z,relro,-z,now Makes the relocation table read-only after startup

None of these fix a bug. They raise the cost of exploiting one. In development, add the sanitizers from the Debugging lesson (-fsanitize=address,undefined), which find the bug itself. Sanitizers slow programs down too much for production, so use them in tests; keep the hardening flags in release builds.

Habits that keep code safe

  • Treat all external input as hostile: validate length, range and format before use.
  • Prefer the standard containers and strings to raw arrays; prefer std::unique_ptr to new.
  • Initialize every variable; use {} initialization.
  • Avoid reinterpret_cast, C-style casts and memcpy on non-trivial types; use std::bit_cast for reinterpreting bits.
  • Keep const on everything that doesn't change, and small functions with one clear owner for each resource.
  • Run tests under AddressSanitizer and UBSan, and fuzz any parser that reads untrusted data (libFuzzer works with -fsanitize=fuzzer,address).
  • Compile with warnings as errors, and run a static analyzer such as clang-tidy or the compiler's -fanalyzer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function signature is safest for code that only reads a sequence of ints?

    A span carries the pointer and the length as one object, so the length cannot be mismatched or forgotten.
  2. 2. What does v.at(i) do when i is out of range for a std::vector?

    at() performs a bounds check and throws std::out_of_range, whereas operator[] has undefined behavior for a bad index.
  3. 3. Why is std::string_view v = std::string{"hi"}; followed by a use of v a bug?

    A string_view does not own its characters. The temporary string dies at the end of the full expression, leaving the view pointing at freed memory.
  4. 4. What is the main purpose of defining _GLIBCXX_ASSERTIONS in a release build?

    The macro adds cheap precondition checks to the library, so a bug stops the program at once rather than silently corrupting memory.
  5. 5. In the plain comparison -1 < 5u, why is the result false?

    The usual arithmetic conversions turn -1 into 4294967295 (for a 32-bit unsigned), which is larger than 5. std::cmp_less compares the mathematical values.

Summary

  • Memory-safety bugs are undefined behavior; prevent them by design, add checks, then detect leftovers with tools.
  • Lifetimes: return owning types, accept views as parameters, never keep references or views past the owner or past container modification.
  • Bounds: prefer range-for, algorithms and std::span; use at() for untrusted indexes; replace C strings and raw buffers with std::string and std::vector.
  • Integers: check multiplications before they happen, use std::in_range and std::cmp_less, and watch for signed/unsigned mixes.
  • Define _GLIBCXX_ASSERTIONS (or libc++ hardening) to turn misuse into an abort.
  • Release builds should use stack protector, _FORTIFY_SOURCE, PIE and full RELRO; development builds should use the sanitizers.

Next: read I/O Streams in Depth, where untrusted input meets cin, stream states and parsing.