Leanpub Header

Skip to main content

Modern C++ Memory Safety

Safer Systems Software Without a Full Rewrite

Modern C++ Memory Safety
This book is 100% completeLast updated on 2026-09-26

Modern C++ Memory Safety shows you how to make existing C++ systems safer without starting over. Learn practical ways to find and fix memory safety issues using modern C++, compiler tools, sanitizers, static analysis and fuzzing, with techniques you can apply directly to real production code.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
156
Pages
About

About

About the Book

This book is a practical engineering guide for reducing memory safety vulnerabilities in existing C++ systems through incremental modernization. It covers the root causes of common vulnerabilities, modern C++ features that eliminate them, compiler diagnostics and sanitizers, static analysis, fuzzing, runtime mitigations and real-world strategies for assessment, refactoring and continuous improvement. The code examples are complete, fully working and designed to translate directly into production systems.

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience in software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. Throughout his career, he has designed, secured, analyzed and tested complex software and infrastructure, with a particular focus on understanding how systems fail and how they can be made more secure.

Outside of work, Steve enjoys sharing knowledge with the technology community. He collaborates with researchers, industry experts and technology professionals to write practical books covering software development, cybersecurity, cloud computing, networking, DevOps, artificial intelligence and enterprise technologies. His books focus on practical learning through clear explanations, real-world examples and hands-on exercises. With more than two decades of industry experience, his goal is to help IT professionals, students and technology enthusiasts build useful skills and stay current in a rapidly changing industry.

We believe readers deserve to know how our books are created. Most of our authors are not native English speakers, so we use AI to help translate, proofread manuscripts, fix grammar, improve sentence structure and make technical explanations easier to read. AI is used as an editing tool only. It does not replace the research, technical knowledge or hands-on experience behind our books. Some of our authors also prefer to remain anonymous for privacy or professional reasons. In those cases, we publish their work under a different name. The author's name may be different, but the quality of the content and our review process remain the same.

Every book is written, reviewed and maintained by experienced technology professionals, with contributions from our private technical community of more than 420 engineers and researchers. We spend far more time validating technical accuracy and keeping our content up to date than generating text. We are always interested in working with experienced professionals who have deep expertise in a particular technology or domain. If you would like to publish a book with us or help review an existing manuscript, we'd love to hear from you. Send us a message describing your area of expertise. We are especially interested in niche technologies, specialized skills and emerging topics that are underrepresented in existing technical literature.

If you look through the contents of our books, you'll see practical examples, detailed explanations and material that is regularly updated. Our goal is to publish books that professionals can actually rely on, not low-effort AI-generated content. If you ever feel that one of our books does not meet that standard, Leanpub offers a 60-day money-back guarantee. Feel free to request a refund if you are not satisfied with your purchase.

Contents

Table of Contents

Safer Systems Software Without a Full Rewrite

Introduction: The Memory Safety Problem in C++

  1. The Scale of the Problem
  2. Why C++ Gets Memory Safety Wrong
  3. The Full Rewrite Fallacy
  4. What This Book Will Give You

Chapter 1: How Memory Safety Failures Happen

  1. The C++ Memory Model in Practice
  2. Pointers, References, and Their Promises
  3. Object Lifetimes and Aliasing
  4. Undefined Behavior as the Root Cause
  5. From Bug to Exploit

Chapter 2: Buffer Overflows and Out-of-Bounds Access

  1. Mechanics of Buffer Overruns
  2. Stack and Heap Smashing
  3. Off-by-One and Off-by-Many Errors
  4. Modern C++ Bounds-Safe Patterns
  5. Refactoring C-Style Arrays and Pointers

Chapter 3: Use-After-Free and Dangling References

  1. How Use-After-Free Occurs
  2. Exploitation: Heap Feng Shui and Function Pointer Overwrite
  3. Dangling References and Iterators
  4. RAII as the Foundation
  5. Smart Pointer Semantics and Ownership

Chapter 4: Double Free and Memory Leaks

  1. The Double Free Mechanism
  2. Exploiting Double Free for Arbitrary Write
  3. Memory Leaks: Not Just a Performance Problem
  4. Allocators and Lifetime Guarantees

Chapter 5: Uninitialized Memory and Data Leaks

  1. Stack and Heap Uninitialized Memory
  2. Information Leaks Through Uninitialized Buffers
  3. Aggregate Initialization and Value Initialization
  4. Modern Defaults: Constructors and std::optional
  5. Zero-Cost Safety Guarantees

Chapter 6: Iterator Invalidation and Container Safety

  1. How Iterator Invalidation Occurs
  2. Consequences Across Standard Containers
  3. Safe Patterns and Range-Based Alternatives
  4. C++20 Ranges for Safer Algorithms
  5. Real-World Refactoring Examples

Chapter 7: Type Confusion and Variant Safety

  1. Polymorphic Type Confusion
  2. Union-Based Type Confusion in C-Style APIs
  3. std::variant and std::any for Type-Safe Unions
  4. Virtual Tables and Their Assumptions
  5. Safe Casting: dynamic_cast and Alternatives

Chapter 8: Concurrency-Related Memory Errors

  1. Data Races Are Undefined Behavior
  2. False Sharing and Memory Ordering Pitfalls
  3. std::atomic and Correct Concurrent Programming
  4. Threading Primitives and Memory Guarantees
  5. Lock-Free Data Structures and Their Dangers

Chapter 9: The RAII Idiom in Depth

  1. RAII Origins and Philosophy
  2. Resource Scope and Deterministic Cleanup
  3. RAII for Non-Memory Resources
  4. Exception Safety and RAII Guarantees
  5. RAII Wrappers for Legacy C APIs

Chapter 10: Ownership, Move Semantics, and Value Semantics

  1. Unique Ownership and std::unique_ptr
  2. Shared Ownership and std::shared_ptr
  3. Move Semantics for Efficient Ownership Transfer
  4. Value Semantics for Safer APIs
  5. Ownership Documentation and Contracts

Chapter 11: Bounds-Safe Interfaces and std::span

  1. The Problem with (pointer, size) Pairs
  2. std::span as a View Type
  3. Migrating C APIs to Span-Based Interfaces
  4. std::string_view for String Handling
  5. Performance Characteristics and ABI Implications

Chapter 12: Modern Containers and Allocators

  1. Container Choice and Safety Implications
  2. Custom Allocators for Control
  3. Memory Pools for Performance and Safety
  4. Container Growth and Invalidation Guarantees
  5. Safe Interoperability with C Allocators

Chapter 13: Exception Safety and Its Role in Memory Safety

  1. Exception Safety Levels and Memory Leaks
  2. Strong and Basic Guarantees in Practice
  3. RAII Under Exceptions
  4. Nothrow Operations and Performance-Critical Code
  5. Handling Exceptions in C-API Boundaries

Chapter 14: Assessing Your Legacy Codebase

  1. Establishing a Security Baseline
  2. Static Risk Indicators in Code
  3. Runtime Profiling for Dangerous Patterns
  4. Prioritization Frameworks
  5. Mapping Dependencies and Blast Radius

Chapter 15: Incremental Modernization Strategies

  1. The Facade Pattern for Gradual Modernization
  2. Building Safe Envelopes Around Unsafe Code
  3. Header-Only Modernization Libraries
  4. ABI Compatibility and Versioning
  5. Managing Technical Debt and Scope

Chapter 16: Refactoring Patterns for Safer C++

  1. Migrating from Raw Pointers to Smart Pointers
  2. Eliminating C-Style String APIs
  3. Safe Memory Copy Patterns
  4. Refactoring Callbacks and Function Pointers
  5. Real-World Before-and-After Case Studies

Chapter 17: Compiler Diagnostics and Warnings

  1. GCC, Clang, and MSVC Warning Flags
  2. Enforcing Warnings as Errors
  3. Compiler-Specific Diagnostics for Memory Safety
  4. Incremental Warning Adoption
  5. Suppression Strategies That Do Not Harm

Chapter 18: Sanitizers for Development and Testing

  1. AddressSanitizer Configuration and Interpretation
  2. UndefinedBehaviorSanitizer for Pre-Exploit Detection
  3. MemorySanitizer for Uninitialized Memory
  4. ThreadSanitizer for Data Race Detection
  5. Performance Overhead and Practical Usage

Chapter 19: Static Analysis for Large Codebases

  1. clang-tidy and Its Safety Checks
  2. Cppcheck and Other Static Analyzers
  3. Integrating Analysis into CI Pipelines
  4. Tuning for Signal Over Noise
  5. Understanding False Positives and False Negatives

Chapter 20: Fuzzing and Dynamic Testing

  1. LibFuzzer for C++ Codebases
  2. AFL++ and Other Fuzzing Frameworks
  3. Designing Fuzz Targets for Existing APIs
  4. Integrating Fuzzing with Sanitizers
  5. From Bug Discovery to Remediation

Chapter 21: Runtime Mitigations and Hardened Deployments

  1. ASLR, Stack Canaries, and NX Bits
  2. Control-Flow Integrity Mechanisms
  3. Hardened Standard Library Implementations
  4. Containerization and Namespace Isolation
  5. Limitations and Defense-in-Depth

Chapter 22: Automated Refactoring and Tool-Assisted Migration

  1. Clang-Tidy’s Modernization Checks
  2. Automated Smart Pointer Migration
  3. Coccinelle and Semantic Patching
  4. Refactoring Large Teams and Codebases
  5. Validating Automated Changes

Chapter 23: Measuring Progress and Continuous Improvement

  1. Safety Metrics That Matter
  2. Baseline and Trend Measurement
  3. Security Testing in CI/CD
  4. Regression Prevention
  5. Building a Safety Culture

Chapter 24: Case Study: Modernizing a Network Server

  1. Legacy Codebase and Risk Profile
  2. Initial Assessment and Tooling Setup
  3. Phased Refactoring Plan
  4. Measuring the Safety Improvements
  5. Lessons and Generalizations

Chapter 25: Case Study: Storage Engine Safety

  1. Memory Safety Challenges in Storage Systems
  2. Lifetime Management in B-Tree Structures
  3. Concurrent Access and Iterator Safety
  4. Allocator Design for Safety and Performance
  5. Validation and Deployment

Conclusion: The Road Ahead

  1. What We Have Learned
  2. Emerging C++ Safety Features
  3. The Economics of Incremental Modernization
  4. Final Recommendations

References

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

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.)

In fact, authors have earned over $15 million writing, publishing and selling 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