Memory Safety in C++
C++ has one weapon C lacks: RAII — Resource Acquisition Is Initialisation. Bind resource lifetimes to object lifetimes and the compiler cleans up after you, even on the unhappy path. Whole categories of bugs simply stop happening, provided you use the tools consistently.
RAII: The Foundation of Safety
The shape of RAII: constructors acquire, destructors release. C++ guarantees destructors fire on scope exit — including the chaos of exception unwinding — so resources go back where they came from regardless of how control leaves the scope:
#include <fstream>#include <memory>#include <vector>
void safe_function() { // File closed automatically when f goes out of scope std::ifstream f("data.txt");
// Memory freed automatically when v goes out of scope std::vector<int> v(1000);
// Even if an exception is thrown here, everything is cleaned up if (v.empty()) throw std::runtime_error("unexpected");
} // Destructors run here: vector freed, file closedSmart Pointer Discipline
Rule: stop typing new and delete. Smart pointers handle the bookkeeping:
#include <memory>#include <iostream>
struct Widget { std::string name; Widget(std::string n) : name(std::move(n)) { std::cout << "Created " << name << "\n"; } ~Widget() { std::cout << "Destroyed " << name << "\n"; }};
void demo() { // Unique ownership auto w1 = std::make_unique<Widget>("sole owner"); // w1 automatically deleted at end of scope
// Shared ownership auto w2 = std::make_shared<Widget>("shared"); auto w3 = w2; // Reference count: 2 // Deleted when last shared_ptr is destroyed
// Transfer ownership auto w4 = std::make_unique<Widget>("transferred"); auto w5 = std::move(w4); // w4 is now nullptr}std::unique_ptr costs you nothing. Same size as a raw pointer, identical codegen on any decent optimiser. Reaching for raw new/delete in modern C++ is just typing more characters for fewer guarantees.
When to Use Which Smart Pointer
| Type | When to Use |
|---|---|
unique_ptr | Default choice. Single owner. Zero overhead. |
shared_ptr | Multiple owners needed (rare). Has overhead (reference count). |
weak_ptr | Breaking cycles in shared_ptr graphs. Observer pattern. |
| Raw pointer | Non-owning reference to an existing object. Never for ownership. |
| Reference | Non-owning, non-nullable reference. Preferred over raw pointer. |
Avoiding Raw new/delete
// BAD: raw new/deleteWidget* w = new Widget("bad");// ... if exception thrown here, memory leaksdelete w;
// GOOD: make_uniqueauto w = std::make_unique<Widget>("good");// Automatically deleted, even on exception
// BAD: raw new for arrayint* arr = new int[100];delete[] arr; // Must use delete[], not delete
// GOOD: vectorstd::vector<int> arr(100);
// GOOD: unique_ptr for arrayauto arr = std::make_unique<int[]>(100);std::span for Bounds Safety (C++20)
std::span is a fat pointer in disguise: a base pointer plus a length, owning nothing:
#include <span>#include <vector>#include <iostream>
// Accepts any contiguous containervoid process(std::span<const int> data) { for (int x : data) { std::cout << x << " "; } std::cout << "\n";
// operator[] isn't bounds-checked by the standard: data[100] is UB. // Turn on library checks to trap it (see below), or use data.at(100) // in C++26.}
int main() { std::vector<int> v = {1, 2, 3, 4, 5}; process(v);
int arr[] = {10, 20, 30}; process(arr);
// Subspan process(std::span(v).subspan(1, 3)); // 2 3 4 return 0;}span retires the venerable (pointer, length) pair — the same pattern that gave us a generation of buffer overflows in C.
Keeping the length next to the pointer only helps if something checks it. Plain span::operator[] doesn't, any more than vector::operator[] does. Build with -D_GLIBCXX_ASSERTIONS (libstdc++) or -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST (libc++) and out-of-range [] on span, vector, string and array aborts instead of reading past the end. The checks are cheap enough that Fedora builds its packages with the libstdc++ one switched on.
Container Safety
// BAD: unchecked array accessint arr[10];arr[15] = 42; // Buffer overflow, undefined behavior
// GOOD: vector with at() for bounds checkingstd::vector<int> v(10);try { v.at(15) = 42; // Throws std::out_of_range} catch (const std::out_of_range& e) { std::cerr << "Out of bounds: " << e.what() << "\n";}
// GOOD: operator[] in performance-critical code// (but validate index first)size_t idx = get_index();if (idx < v.size()) { v[idx] = 42;}String Safety
// BAD: C-style string manipulationchar buf[32];strcpy(buf, very_long_string); // Buffer overflow
// GOOD: std::string handles memory automaticallystd::string s = very_long_string; // Grows as needed
// GOOD: string_view for non-owning referencesvoid process(std::string_view sv) { // No allocation, no copy auto sub = sv.substr(0, 10);}
// BAD: string_view outliving the string it points intostd::string_view first_word() { std::string s = read_line(); return std::string_view(s).substr(0, s.find(' ')); // s dies here}Lifetime Bugs RAII Won't Catch
Smart pointers and containers stop leaks and double frees. They don't stop you holding a non-owning view into something that's gone, and that's where most modern C++ use-after-free bugs live:
// Iterator invalidation: push_back may reallocate, leaving it danglingstd::vector<int> v = {1, 2, 3};auto it = v.begin();v.push_back(4);*it = 10; // use-after-free if the vector grew
// References into containers have the same problemint& first = v[0];v.clear();first = 5; // dangling
// Lambdas capturing locals by referencestd::function<int()> make_counter() { int count = 0; return [&count] { return ++count; }; // count dies on return}The pattern is always the same: a pointer, reference, iterator, string_view or span that doesn't own its target. Capture by value when a lambda outlives the scope, re-fetch iterators after anything that can resize, and treat non-owning views as function parameters rather than things you store. ASan's heap-use-after-free and stack-use-after-return reports are how you find the ones that slip through.
Factory Functions
Module 5 had constructors throw when they couldn't establish their invariant, and that's the default in code that uses exceptions. When a project builds with -fno-exceptions, or failure is routine rather than exceptional (a host that's down, a file that isn't there), push the failure into a factory function instead, so the caller has to check the result:
class Connection { int fd_; Connection(int fd) : fd_(fd) {}
public: static std::unique_ptr<Connection> create(const std::string& host) { int fd = connect_to(host); if (fd < 0) return nullptr; return std::unique_ptr<Connection>(new Connection(fd)); }
~Connection() { if (fd_ >= 0) close(fd_); }
// Non-copyable; move the unique_ptr, not the Connection Connection(const Connection&) = delete; Connection& operator=(const Connection&) = delete;};The Rule of Five/Zero
Define one of destructor, copy ctor, copy assignment, move ctor, or move assignment, and you've taken responsibility for all five (Rule of Five). Hold only standard library types and smart pointers, though, and you write none (Rule of Zero) — the compiler-generated specials already do the right thing:
// Rule of Zero - best practiceclass UserProfile { std::string name_; std::unique_ptr<Image> avatar_; std::vector<Post> posts_; // Compiler-generated special members do the right thing};Lean on these patterns and your C++ approaches managed-language safety without surrendering the performance that brought you to C++ in the first place.
Challenges
Convert a function that uses raw new/delete into one using std::unique_ptr. The function creates an array of 5 ints, sets them to 1-5, prints the sum, and the memory is automatically freed. Print the sum.