liveBook · Manning

Alloc crate

As explained in Embedded Software with Rust

Rust’s allocation library, providing heap-allocated collections and related types when an allocator is available.

The Rust alloc crate provides heap-allocated types such as Box, Vec, String, Rc, Arc, and BTreeMap. In no_std firmware, core supplies language fundamentals without a heap; alloc is optional and requires an explicitly installed global allocator. section 7.1.2

To use alloc, declare extern crate alloc at the crate root, reserve RAM for the heap, and initialize a global allocator before allocating. On Cortex-M, embedded-alloc provides an LlffHeap allocator; it also requires a critical-section implementation. section 7.1.2 section 7.2.2

#![no_std]
#![no_main]

extern crate alloc;

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use cortex_m_rt::entry;
use embedded_alloc::LlffHeap as Heap;

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

fn record_event(log: &mut Vec<String>, source: &str, code: u32) {
    log.push(format!("{}: code 0x{:08x}", source, code));
}

#[entry]
fn main() -> ! {

    unsafe { embedded_alloc::init!(HEAP, 4096); }

    let mut log: Vec<String> = Vec::new();

    record_event(&mut log, "uart", 0x0001);
    record_event(&mut log, "i2c",  0x002a);
    record_event(&mut log, "gpio", 0x00ff);

    for entry in &log {
        defmt::info!("{}", entry.as_str());
    }

    loop {}
}

This firmware example initializes a 4 KiB heap, then records formatted diagnostic messages in a Vec<String>. Each formatted message allocates a String; growing the vector can also allocate a larger backing array. section 7.2.4

Heap space is limited, and fragmentation can cause an allocation to fail. Ordinary allocation APIs route failure through the panic handler; use fallible methods such as Vec::try_reserve when a code path needs to handle insufficient capacity. section 7.0 section 7.2.4

let mut v: Vec<u32> = Vec::new();

// Try to ensure capacity for 1024 elements.
// Returns Err(TryReserveError) if the allocator cannot satisfy the request.
match v.try_reserve(1024) {
    Ok(()) => {
        for i in 0..1024 { v.push(i); }
    }
    Err(_) => {
        // Recover gracefully: log, fall back to a smaller buffer, retry later.
    }
}

This example reserves vector capacity before filling it and handles an unsuccessful reservation instead of continuing as though space were available. section 7.2.4

Prefer stack or static storage when a heap is unnecessary. Fixed-capacity containers from heapless or arrayvec avoid heap allocation; hybrid containers from smallvec or tinyvec can use inline storage but still require an allocator for overflow. section 7.1.2 section 7.5

How Embedded Software with Rust covers it

How deep it goes
Explains allocator setup, vector growth, allocation failure, and fallible reservation, alongside heap-free alternatives.
Examples
Uses a dynamically growing diagnostic message log and a vector reservation that handles insufficient capacity.
What you can do after
Apply alloc via embedded-alloc to initialize a heap and use dynamic collections in firmware.
How it connects
Connects alloc to core, global allocators, heap fragmentation, fixed-capacity containers, and panic handling.

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.