liveBook · Manning

Memory allocator

As explained in Embedded Software with Rust

A memory-management component that reserves and releases dynamically managed storage.

A memory allocator manages heap storage for data whose size or lifetime cannot be known at compile time. In no_std firmware, the heap is optional: reserve RAM for it and install an allocator. Heap flexibility comes with runtime overhead, non-deterministic timing, fragmentation risk, and added power draw. Manual C-style allocation is possible in Rust, but idiomatic Rust rarely uses it. section 7.1 section 7.1.1

The embedded-alloc crate offers two allocator strategies for Cortex-M:

  • LlffHeap uses linked-list first-fit allocation; it is the simpler default starting point. section 7.2.2
  • TlsfHeap adds code size and bookkeeping in exchange for better worst-case allocation times and lower fragmentation on long-running workloads. section 7.2.2
#![no_std]
#![no_main]

extern crate alloc;

use core::mem::MaybeUninit;
use cortex_m_rt::entry;
use embedded_alloc::LlffHeap as Heap;

#[global_allocator]
static HEAP: Heap = Heap::empty();

#[entry]
fn main() -> ! {
    // Reserve 4 KiB of RAM for the heap. MaybeUninit lets us
    // declare an uninitialized array.
    const HEAP_SIZE: usize = 4096;
    static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] =
        [MaybeUninit::uninit(); HEAP_SIZE];

    // Initialize the allocator before any code that allocates runs.
    unsafe {
        HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE);
    }

    // From this point on, Box::new, Vec::push, String::from,
    // etc. all work.
    loop { /* application code */ }
}

A complete no_std setup declares a global allocator, reserves 4 KiB of MaybeUninit backing memory, and initializes it before allocating. section 7.2.2

The setup also requires a critical-section implementation because embedded-alloc serializes allocation and deallocation internally. On Cortex-M, the cited approach enables critical-section-single-core on the cortex-m crate. section 7.2.2

How Embedded Software with Rust covers it

How deep it goes
Explains heap trade-offs and allocator setup, but limits implementation detail to brief summaries of two strategies.
Examples
Compares first-fit and TLSF strategies and shows a 4 KiB Cortex-M global-heap setup.
What it assumes
Builds shared memory-region vocabulary before allocation and uses Cortex-M for the concrete global-allocator setup.
What you can do after
Operate/configure a global embedded-alloc heap by reserving backing RAM, initializing it early, and providing critical-section support.
How it connects
Connects heap allocation to no_std, the alloc crate, MaybeUninit, and critical sections.

Also explained in

Compare how 4 books explain memory allocator →

Related concepts

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