chapter six

6 Memory

 

In this chapter:

  • What a pointer is and why some of them are “smart”
  • What the terms “the stack” and “the heap” mean
  • How a program views its memory and why that’s a lie

The chapter provides you with some of the tacit knowledge held by systems programmers about how the computer’s memory operates. It aims to be the most accessible guide to pointers and memory management available. You will be learning about how applications interact with an operating system. Programmers who understand these dynamics can use that knowledge to maximize their programs' performance, while minimizing their memory footprint.

Memory is a shared resource and the operating system is an arbiter. To make its life easier, it lies to your program about how much memory is available and where it’s located. Revealing the truth behind those lies requires us to work through some prior knowledge. That is the work of the first two sections of the chapter. Each of the three sections builds on the previous one.

None of them assume that you’ve encountered the topic before. There is a fairly large body of theory to cover, but all of it is explained by example. Among other examples, you create your first graphical application in the book.

The chapter introduces little new Rust syntax, as the material is quite dense. You’ll learn how to construct pointers, how to interact with an operating system via its native API and how to interact with other programs through Rust’s foreign function interface.

6.1  Pointers

6.2  Exploring Rust’s reference and pointer types

6.2.1  Raw pointers in Rust

6.2.2  Rust’s pointer ecosystem

6.2.3  Smart pointer building blocks

6.3  Providing programs with memory for their data

6.3.1  The stack

6.3.2  The heap

6.3.3  What is dynamic memory allocation?

6.4  Virtual Memory

6.4.1  Background

6.4.2  Step 1: Having a Process Scan Its Own Memory

6.4.3  Translating virtual addresses to physical addresses

6.4.4  Step 2: Working with the operating system to scan an address space

6.4.5  Step 3: reading and writing bytes to processes' memory

6.5  Wrap up