Leanpub Header

Skip to main content

Memory-Safe C++ in Production

Enforcing Bounds and Lifetime Safety Through Hardened Libraries and Sanitizer-Driven Development

Memory-Safe C++ in Production
This book is 100% completeLast updated on 2026-11-22

A length field off the wire that nobody checked. A reference held across a push_back. A lambda that fires five seconds after its session is gone. None of these memory bugs is exotic, and each one can sit in production for months, silently corrupting memory. Memory-Safe C++ in Production takes one realistic C++ service from a baseline full of seeded defects to a hardened, continuously tested system. You'll use hardened standard libraries, C++26 contracts, sanitizers, fuzzing, static analysis and production mitigations, and every cost is measured as you go. By the end, each bug class is fixed so it can't come back, and the bugs that slip through anyway end in a trap instead of an exploit.

Free With Membership

With Membership

Free!

$39.99

You pay

Author earns

$

Also available for 2 book credits with a Reader Membership

PDF
About

About

About the Book

Most of a large C++ codebase's serious security bugs come from a short list of failures: an index one past the end, a reference kept after its object is gone, a cast that trusts the wrong field, a value nobody initialized, a race on a shared string. Large vendors keep reporting that memory-safety issues make up the majority of their high-severity vulnerabilities. The tools that prevent most of them already exist. Most teams just don't use them every day.

Memory-Safe C++ in Production shows you how to use them every day.

You won't get a lecture on best practices. You'll take one realistic service and harden it from start to finish. relay is a network-facing message gateway with an untrusted input boundary, shared state across threads, hot paths where every check has a cost, and third-party code nobody owns. It ships with eight seeded memory bugs, one or more for each bug class, plus two that aren't listed. Over thirteen chapters you'll find them, fix them so their whole class can't come back, and build the tooling that catches the next one before it reaches production.

Every chapter ends with the Safety Ledger, a running record of what relay now enforces, what detects each bug class, which defects are still open, and what each step cost in measured performance. You always know what changed, what it bought and what it cost.

What you'll learn

  • Make spatial errors impossible to write. Use span-based interfaces, hardened libc++ and libstdc++ modes, C++26 contracts, Clang's Safe Buffers and checked parsing at the network boundary. Then measure the real cost of bounds checks, which is usually within noise, and fix the few that aren't.
  • Control lifetimes. Deal with dangling views, iterator invalidation, escaping lambdas, coroutine lifetime traps, shared_ptr cycles and use-after-move. Back up the fixes with explicit ownership, generational handles, arenas and compiler lifetime annotations.
  • Close the quiet bug classes. Cover type confusion, strict aliasing, unions versus std::variant, C++26 erroneous behavior, automatic variable initialization and checked integer arithmetic.
  • Build a sanitizer-first workflow. Run ASan, UBSan, MSan, TSan and HWASan on every build. Put GWP-ASan in production. Add static analysis with custom clang-tidy checks, and coverage-guided, stateful and differential fuzzing that runs continuously.
  • Harden what survives. Add stack protectors, _FORTIFY_SOURCE, control-flow integrity, shadow stacks, hardened allocators and ARM Memory Tagging, and verify all of it on the binary you actually ship.
  • Migrate real codebases. Audit by exposure. Define a safe subset the build enforces. Apply refactoring patterns that remove whole bug classes. Build safe C++/Rust interop with cxx. Decide rewrite versus harden honestly, one component at a time.
  • Run it as a program. Track metrics that can't be gamed, set up CI/CD safety gates and canary comparison, follow an incident runbook for memory corruption, and write a multi-year roadmap for a real organization.

What makes this book different

  • Every claim can be checked. Costs are measured with a stated protocol and reported as ranges, never as one convenient number from one machine.
  • Every technique is applied to real code that builds, runs and is tested under sanitizers. There is no pseudocode.
  • It's honest about limits. Hardened C++ is not memory-safe by construction, and the book says exactly where the remaining risk lives and how to contain it.
  • It covers the whole lifecycle, from the first build flag to production detection, incident response and the decision to rewrite.

Who it's for

The book is for engineers who ship and maintain production C++: application and systems developers, tech leads, security engineers and platform teams. You should know modern C++. You don't need prior experience with sanitizers, fuzzers or the memory model. Each tool is introduced from first principles before you rely on it.

Four reference appendices come with the book: a sanitizer and hardening flag reference, an undefined behavior catalog, a static analysis check reference and a memory safety audit checklist you can run on your own codebase tomorrow.

Share this book

Author

About the Author

Weston Ashgrove

Weston Ashgrove is a C++ systems engineer who builds software where being wrong or slow has a cost. He came up through quantitative trading, building order books, matching logic and the low-latency infrastructure underneath them and now brings the same discipline to performance engineering, concurrency, storage, networking, GPUs, and AI inference.

His rule for performance-critical code is simple: nothing is true until it has been profiled, fuzzed, and replayed. Every technique in his books comes with the measurement that proves it, the trade-off it costs, and the failure it prevents. He writes for working engineers who ship and debug production C++, and he leaves out anything that only works on a slide.

Contents

Table of Contents

Table of Contents

Front Matter
  • Preface
  • Who This Book Is For
  • What You Will Build
  • What You Need
  • How to Read This Book
  • Conventions
Part I: The Foundations
  • Chapter 1: Memory Safety and Undefined Behavior
    • 1.1 Anatomy of Memory Bugs: Spatial, Temporal, Type, and Initialization Errors
    • 1.2 What Undefined Behavior Means to the Optimizer
    • 1.3 Erroneous Behavior in C++26 and the End of Uninitialized Reads as UB
    • 1.4 The Reference Codebase and the Safety Baseline
Part II: Spatial Safety
  • Chapter 2: Bounds Safety
    • 2.1 std::span, std::array, and Bounds-Aware Interfaces
    • 2.2 Hardened Standard Library Modes in libc++ and libstdc++
    • 2.3 Contracts and Hardened Preconditions in C++26
    • 2.4 Compiler-Enforced Bounds Safety and Bounds Annotations
    • 2.5 Measuring the Real Cost of Bounds Checks
  • Chapter 3: Strings and Buffers
    • 3.1 Replacing C String APIs with std::string, std::format, and std::print
    • 3.2 Buffer Handling at API and Network Boundaries
Part III: Temporal and Type Safety
  • Chapter 4: Lifetime Safety
    • 4.1 Dangling References, Views, Iterators, and string_view
    • 4.2 Iterator Invalidation Rules That Bite in Production
    • 4.3 Lifetime Annotations and Compiler Lifetime Analysis
    • 4.4 Lifetimes Across Lambdas, Callbacks, and Coroutines
  • Chapter 5: Ownership
    • 5.1 Ownership Models: Unique, Shared, Borrowed, and Arena-Owned
    • 5.2 shared_ptr Cycles, weak_ptr, and Hidden Ownership Costs
    • 5.3 Use-After-Move and Moved-From State
  • Chapter 6: Type and Initialization Safety
    • 6.1 Casts: reinterpret_cast, std::bit_cast, and Type Punning
    • 6.2 Unions vs. std::variant
    • 6.3 Strict Aliasing and Object Lifetime Rules
    • 6.4 Automatic Variable Initialization and -ftrivial-auto-var-init
    • 6.5 Integer Overflow, Narrowing, and Safe Arithmetic
Part IV: Tooling
  • Chapter 7: Sanitizer-Driven Development
    • 7.1 AddressSanitizer, UndefinedBehaviorSanitizer, and MemorySanitizer
    • 7.2 HWASan and Production Sanitizers with GWP-ASan
    • 7.3 A Development Workflow Built Around Sanitizers
  • Chapter 8: Static Analysis
    • 8.1 clang-tidy and the Clang Static Analyzer
    • 8.2 The C++ Core Guidelines and Safety Profiles
    • 8.3 Custom Checks and Triaging False Positives
  • Chapter 9: Fuzzing
    • 9.1 libFuzzer and AFL++
    • 9.2 Structure-Aware Fuzzing
    • 9.3 Continuous Fuzzing in CI
Part V: Hardening at Scale
  • Chapter 10: Compiler and Runtime Hardening
    • 10.1 Stack Protectors and _FORTIFY_SOURCE
    • 10.2 Control-Flow Integrity and Shadow Stacks
    • 10.3 Hardened Allocators: Scudo and Hardened malloc
    • 10.4 ARM Memory Tagging Extension
  • Chapter 11: Concurrency Safety
    • 11.1 Data Races as Memory Safety Bugs and ThreadSanitizer
    • 11.2 Ownership Transfer and Safe Shared State Across Threads
    • 11.3 Thread-Safety Annotations and Capability Analysis
  • Chapter 12: Migration and Interop
    • 12.1 Auditing a Legacy Codebase and Prioritizing by Exposure
    • 12.2 Safe Subsets and Refactoring Patterns That Remove Whole Bug Classes
    • 12.3 C++ and Rust Interop with cxx and Safe FFI Boundaries
    • 12.4 Rewrite vs. Harden: An Honest Decision Framework
Part VI: Production
  • Chapter 13: Memory Safety in Production
    • 13.1 Defect Metrics That Mean Something
    • 13.2 Safety Gates in CI/CD
    • 13.3 Incident Response for Memory Corruption Bugs
    • 13.4 The Memory Safety Roadmap for a Real Organization
Appendices
  • Appendix A: Sanitizer and Hardening Flag Reference
  • Appendix B: Undefined Behavior Catalog
  • Appendix C: Static Analysis Check Reference
  • Appendix D: Memory Safety Audit Checklist
About the Author

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub