chapter five

5 Working with memory

 

This chapter covers

  • Learning about heap and stack-based memory management details in Rust
  • Understanding Rust’s ownership semantics
  • Using reference counted pointers
  • Effectively utilizing smart pointers
  • Implementing custom allocators for specific use cases

In chapter 4 we discussed Rust’s data structures, but to complete our understanding we also need to discuss memory management and how it works with Rust’s data structures. The core data structures provide nice abstractions for managing memory allocation and deallocation, but some applications may require more advanced features that require custom allocators, reference counting, smart pointers, or system-level features that are outside the scope of the Rust language.

It’s possible to effectively use Rust without having a deep understanding of memory management, but there are many cases in which it’s quite beneficial to know what’s going on beneath the hood, so to speak. In this chapter we’ll get into the details of Rust’s memory management.

5.1 Memory management: heap and stack

Rust has very powerful and fine-grained memory management semantics. You may find, when you’re new to Rust, that it seems somewhat opaque at first. For example, when you use a String or a Vec, you likely aren’t thinking too much about how the memory is allocated. In some ways this is similar to scripting languages such as Python or Ruby where memory management is largely abstracted away, and rarely something you need to think about.

5.2 Understanding ownership: copies, borrowing, references, and moves

5.3 Deep copying

5.4 Avoiding copies

5.5 To box or not to box: smart pointers

5.6 Reference counting

5.7 Clone on write

5.8 Custom allocators

5.8.1 Writing a custom allocator

5.8.2 Creating a custom allocator for protected memory

5.9 Summary