liveBook · Manning

Memory safety

As explained in Refactoring to Rust

Memory safety is the property that software accesses memory only in valid ways, preventing errors such as use-after-free, buffer overflows, and invalid pointer dereferences.

Memory safety means avoiding invalid uses of memory. For a C or C++ application, moving a critical component to Rust can turn some memory bugs—such as dangling pointers and data races—from dangerous runtime failures into compile-time errors. This can be done one component at a time rather than through a full rewrite. section 1.4.2 section 1.6

Ownership is central to those checks. One handle controls when a piece of memory is allocated and deallocated; Rust requires code to follow its ownership rules. The compiler can then reject many bugs that a C or C++ programmer would otherwise have to prevent by tracking ownership manually. section 1.4.2

A dangling-pointer risk

Suppose a component might keep using a pointer after the memory it refers to has been freed. That is the kind of bug safe Rust is designed to reject at compile time. When the component must use memory managed by non-Rust code, however, the compiler cannot verify how that memory was allocated, accessed, or freed. An unsafe block puts responsibility for upholding Rust’s safety rules on the developer. section 1.4.2 section 3.1

Treat safety as a goal to verify throughout an incremental refactor:

  • Choose the parts of an existing C or C++ application where better memory safety matters, and decide how they will communicate with Rust. section 1.6
  • Mirror the existing behavior in Rust and integrate it with the application. section 1.6
  • Test the new functionality and compare results from the old and new code paths before rollout. section 1.6

How Refactoring to Rust covers it

How deep it goes
Explains ownership and compile-time rejection of memory bugs, then identifies the limits of compiler checks for foreign memory.
Examples
Uses dangling pointers and data races as bug examples, alongside an incremental C or C++ refactoring process.
What it assumes
Assumes programming experience outside Rust, while explaining ownership rather than requiring prior Rust expertise.
What you can do after
Apply it via Rust refactoring to reduce memory-bug risks while testing behavior across old and new code paths.
How it connects
Connects memory safety to ownership, lifetimes, foreign function interfaces, raw pointers, and unsafe Rust.

Also explained in

Compare how 3 books explain memory safety →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.