TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Memory-Safe Habits in Modern C++

Memory-Safe Habits in Modern C++

C++ inherited all of C's memory bugs and added a few of its own (type confusion, iterator invalidation, dangling references to temporaries). It also offers what C lacks: types that own memory and release it automatically, containers that know their size, views that carry bounds, and standard libraries that can check every index. Code that uses them consistently has far fewer bugs than "C with classes"; code that mixes them with raw new, raw pointers and C arrays keeps all the old ones. C++ is not memory-safe, and no set of habits makes it so, but the habits below remove most of the bug classes of this course in day-to-day code. The features are taught in C++ Smart Pointers, C++ Vectors and Move Semantics.

RAII and smart pointers: ownership in the type

RAII (resource acquisition is initialisation) ties a resource to an object's lifetime: the constructor acquires, the destructor releases, and the compiler calls the destructor on every exit path, including early returns and exceptions. std::unique_ptr<T> is RAII for one heap object with one owner; std::shared_ptr<T> counts owners; std::weak_ptr<T> observes a shared object without keeping it alive and can tell whether it still exists. Together they make the leak, double free and use-after-free lessons' fixes automatic:

cpp · try it yourself
#include <cstdio>
#include <memory>
#include <optional>
#include <string>

struct Session { std::string user; bool is_admin = false; };

// Returns an owned session, or nothing. No path can leak it.
static std::unique_ptr<Session> load(const std::string &user, const std::string &email) {
    auto s = std::make_unique<Session>();
    s->user = user;
    if (email.find('@') == std::string::npos)
        return nullptr;                       // s is destroyed here automatically
    return s;                                 // ownership moves to the caller
}

int main() {
    auto ok = load("alice", "alice@lab.test");
    auto bad = load("bob", "bob-at-lab.test");
    std::printf("alice: %s, bob: %s\n", ok ? "loaded" : "rejected", bad ? "loaded" : "rejected");

    // A cache observes sessions without owning them.
    std::shared_ptr<Session> live = std::make_shared<Session>(Session{"carol", false});
    std::weak_ptr<Session> cached = live;
    std::printf("cached before logout: %s\n", cached.lock() ? cached.lock()->user.c_str() : "(gone)");
    live.reset();                             // logout: the last owner releases it
    std::printf("cached after logout:  %s\n", cached.lock() ? cached.lock()->user.c_str() : "(gone)");

    std::unique_ptr<Session> a = std::make_unique<Session>();
    std::unique_ptr<Session> b = std::move(a); // exactly one owner at a time
    std::printf("after move: a %s, b %s\n", a ? "owns" : "empty", b ? "owns" : "empty");
    return 0;
}
alice: loaded, bob: rejected
cached before logout: carol
cached after logout:  (gone)
after move: a empty, b owns

The rejected session is freed on the early return without a goto fail. The cache's weak_ptr reports "(gone)" after logout instead of dangling, which is exactly the check the C toy didn't have. A unique_ptr can't be copied, only moved, so two owners can't both free the object.

Bounds: containers, spans and checked access

std::vector, std::string and std::array know their size; std::span<T> (C++20) is a non-owning view that carries a pointer and a length, the C++ version of the length-carrying struct from Safe C Patterns. Their operator[] is unchecked by default, for speed, but two things make bounds checks real:

  • .at(i) always checks and throws std::out_of_range.
  • Hardened standard library modes turn the checks on for operator[], front(), back(), iterator dereferences and more: -D_GLIBCXX_ASSERTIONS for GCC's libstdc++, and -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST (or _EXTENSIVE, _DEBUG) for LLVM's libc++ since version 18. Both are designed to stay on in production, and the C++26 standard adds a "hardened implementation" of the standard library on the same model.

The session reads one element past the end of a std::vector through a std::span, first in a default build, then with libstdc++'s assertions, then under ASan. It runs in your sandbox:

bash · try it yourself
cat > vec.cpp <<'SRC'
#include <cstdio>
#include <span>
#include <vector>

static int sum_first(std::span<const int> s, std::size_t n) {
    int total = 0;
    for (std::size_t i = 0; i < n; i++) total += s[i];   /* BUG: n not checked against s.size() */
    return total;
}

int main() {
    std::setvbuf(stdout, nullptr, _IONBF, 0);
    std::vector<int> scores = {10, 20, 30, 40};
    std::printf("first 4: %d\n", sum_first(scores, 4));
    std::printf("first 5: %d\n", sum_first(scores, 5));
    return 0;
}
SRC
echo "== default build: the bad read goes unnoticed"
g++ -std=c++20 -O1 vec.cpp -o vec && ./vec | head -1
echo "== -D_GLIBCXX_ASSERTIONS (hardened libstdc++)"
g++ -std=c++20 -O1 -D_GLIBCXX_ASSERTIONS vec.cpp -o vec-h && ./vec-h 2>&1 | sed 's/: constexpr.*Assertion/: ... Assertion/'
echo "exit code: ${PIPESTATUS[0]}"
echo "== ASan"
g++ -std=c++20 -g -O1 -fsanitize=address vec.cpp -o vec-a && ./vec-a 2>&1 | grep -E '^first|ERROR|READ|#[01] .*vec.cpp'
== default build: the bad read goes unnoticed
first 4: 100
== -D_GLIBCXX_ASSERTIONS (hardened libstdc++)
first 4: 100
/usr/include/c++/13/span:288: ... Assertion '__idx < size()' failed.
exit code: 134
== ASan
first 4: 100
==29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000020 at pc 0x5729cd56e9a9 bp 0x7ffc7fb88040 sp 0x7ffc7fb88030
READ of size 4 at 0x502000000020 thread T0
    #0 0x5729cd56e9a8 in sum_first /home/learner/vec.cpp:7
    #1 0x5729cd56e9a8 in main /home/learner/vec.cpp:15

The default build reads whatever lies after the vector's storage and prints a sum (cut off here with head -1, because the value is garbage). With _GLIBCXX_ASSERTIONS the span's operator[] checks __idx < size() and aborts before the bad read. The check is a comparison and a branch per access; for most code the cost is in the low single-digit percent, which is why Fedora and RHEL build their packages with it. ASan catches the same read as a heap-buffer-overflow in the vector's storage.

The C++-specific traps

  • Dangling views: std::string_view and std::span don't own. std::string_view v = std::string("tmp"); points into a temporary that dies at the semicolon. Return owning types from functions; use views only as parameters.
  • Iterator and reference invalidation: push_back on a vector may reallocate and invalidate every pointer, reference and iterator into it; erasing from containers invalidates iterators to the erased elements. ASan reports it as heap-use-after-free.
  • this captured in callbacks: a lambda that captures this and outlives the object is a use-after-free. Capture a weak_ptr and lock it.
  • Casts: static_cast downcasts and reinterpret_cast are where type confusion comes from; prefer std::variant, virtual functions or dynamic_cast.
  • Raw new/delete and C arrays in new code: there is almost always a standard type that owns and knows its size.

How unsafe C++ is found

Compiler warnings (-Wall -Wextra, GCC 13's -Wdangling-reference, Clang's -Wdangling family, on by default), clang-tidy's cppcoreguidelines-* and bugprone-* checks (owning raw pointers, pointer arithmetic, C-style casts, bugprone-use-after-move), sanitizers, and hardened standard library modes in tests and production. The C++ Core Guidelines (Stroustrup and Sutter) and their "profiles" proposals describe the safe subset these tools enforce.

Pitfalls

  • shared_ptr everywhere hides ownership instead of designing it, and cycles of shared_ptr leak. Default to unique_ptr; use weak_ptr for back-references.
  • .get() escapes: a raw pointer obtained from a smart pointer and stored somewhere is as dangerous as any raw pointer.
  • Exceptions disabled (-fno-exceptions): .at() can't throw; hardened modes, which abort, still work.

Practice

1. Why does the rejected load("bob", …) not leak, although it returns early?

s is a std::unique_ptr local. On return nullptr; its destructor runs and deletes the Session. No code path can leave the function without destroying it, unless ownership was moved out.

2. What is wrong with std::span evens() { std::vector v = {2, 4}; return v; }?

The span points into v's storage, which is freed when evens returns: a dangling view. Return the std::vector<int> itself.

3. Fix sum_first without relying on a hardened library.

Check the argument: if (n > s.size()) n = s.size(); (or reject), or iterate over s.first(n), which is checked in hardened modes, or simply for (int x : s.first(std::min(n, s.size()))).

Test yourself

What did the weak_ptr report after the last shared_ptr was reset?

  1. carol
  2. (gone): lock() returned an empty pointer instead of dangling
  3. A crash
  4. A copy of the session

What does -D_GLIBCXX_ASSERTIONS change?

  1. Nothing in release builds
  2. It enables bounds and precondition checks in libstdc++, e.g. for span and vector operator[]
  3. It turns on ASan
  4. It disables exceptions

Why can't two std::unique_ptr objects both free the same Session?

  1. They can
  2. unique_ptr can't be copied, only moved, so there is one owner at a time
  3. delete checks for that
  4. The compiler adds a reference count

Which of these is a dangling view?

  1. std::vector<int> v = make();
  2. std::string_view v = std::string("tmp");
  3. std::unique_ptr<int> p = std::make_unique<int>(1);
  4. std::span<int> s(arr); // arr a local array still in scope