liveBook · Manning

Global allocator

As explained in Embedded Software with Rust

The program-wide provider used to allocate and release heap memory.

A global allocator supplies and releases heap memory for a program. In embedded Rust, a no_std build has no default heap: using heap-backed types such as Box, Vec, and String requires the alloc crate, an allocator, and a region of RAM for it to manage. section 1.3.1 section 7.1.2

Choose an allocator implementation and a heap size, then reserve RAM and initialize the allocator before any allocation occurs. Mark the allocator static with #[global_allocator]. Without an allocator, a no_std program using alloc will not link. section 7.2.1 section 7.1.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 */ }
}

This Cortex-M example installs embedded-alloc's LlffHeap, reserves 4 KiB, and initializes it before application code can allocate. MaybeUninit avoids zeroing the heap backing store at startup. section 7.2.2

embedded-alloc also needs a critical-section implementation to serialize allocation and deallocation. On a single-core Cortex-M target, the cortex-m crate's critical-section-single-core feature can provide one. section 7.2.2

Choose heap use deliberately:

  • LlffHeap uses first-fit allocation: it walks a free-block list and takes the first block large enough. TlsfHeap adds code and bookkeeping for better worst-case allocation times and lower fragmentation. section 7.2.2
  • Allocation can fail on a small device. For recoverable growth, try_reserve on Vec, String, and similar types returns a Result. section 7.1.2 section 7.5
  • If fixed capacity is enough, use stack or static storage, or a heap-free container such as heapless or arrayvec. Hybrid containers such as smallvec still need an allocator when they grow onto the heap. section 7.1.2 section 7.5

How Embedded Software with Rust covers it

How deep it goes
Walks through allocator selection, RAM reservation, initialization, synchronization, and allocation failure, with a complete embedded-alloc setup.
Examples
Uses a 4 KiB LlffHeap backing store and compares first-fit and two-level segregated fit allocation.
What it assumes
Assumes familiarity with Rust collections while introducing the missing default heap in no_std from first principles.
What you can do after
Operate and configure embedded-alloc as a global allocator, including its backing RAM and critical-section dependency.
How it connects
Connects dynamic allocation with no_std, the alloc crate, fragmentation, critical sections, and fixed-capacity containers.

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.