Rust's Memory Management System

Feb 2019
[draft, work in progress]


Operating systems provide an abstraction of physical memory to each running program called A Virtual Address Space, for now, assume an address space contains 3 sections:

  • An Instruction section
    Where the program Instructions live.
  • A Stack
    To track function calls, store local variables, function arguments, and return values.
  • A Heap
    For User-managed, dynamically (or runtime) alloacated memory.

The stack is structured to follow a strict first in, last out policy; thus, inserting, deleting, or accessing data on the stack doesnt require intensive computation. However, data stored on the stack must have a known size at compile time that must remain fixed and they cant be used beyond their scope. To address these limitations, we store data of unknown and/or dynamic size on the heap.

Since Heaps lack the determinism of stacks, They cost more to manage and there has been two common approches for managing heap allocated memory:

  • Garbage Collection
    Garbage collected languages manage memory automatically which comes at a runtime performance cost.

  • Manual Management
    Memory is managed exlicity by the programmer. Managing memory manually is an error-prone process that demands careful attention, common bugs include:

    * **Segmentation Faults**  
    Performing an operation on Memory that is was not alloacted.
    * **Buffer Overflow**  
    Alloacted Memory is not enough.   
    * **Memory Leaks**  
    Memory allocated is not freed; and thus, wasted.   
    * **Invalid Access**  
    Attempting to access already dealocated memory, or failing to alloact
    * **free on unallocated memory**  
    Attempting to dealocate already dealocated memory.  

Rust introduces a 3rd novel approch that is not as compuationally expensive as Garbage Collection, and not as error-prone as Dynamic allocation/deallocation: Ownership.


  • A Variable carrying A Value is the Owner of that Value.
  • There can only be one owner at a time.
  • When an owner goes out of scope, the value is dropped

Dropped is rust's term for Deallocated