embedded-alloc supplies a heap for Rust firmware on resource-constrained targets, including Cortex-M systems. It makes alloc types such as Box, Vec, and String usable in no_std builds after a global allocator receives a RAM backing region. section 7.2 section 7.2.2
The usual starting point is LlffHeap with the llff feature. Its linked-list first-fit strategy walks free blocks and takes the first adequate block. TlsfHeap uses extra bookkeeping for better worst-case allocation times and lower fragmentation on long-running workloads. section 7.2.2 section 7.2.5
Install a 4 KiB global heap
Bring alloc into scope, declare an empty static heap with #[global_allocator], reserve RAM as [MaybeUninit<u8>; 4096], and call HEAP.init before allocation begins. MaybeUninit avoids needlessly zeroing the heap during startup. The embedded_alloc::init!(HEAP, 4096) macro hides the declaration and initialization ceremony. A critical-section implementation is also required; Cortex-M projects can enable cortex-m's critical-section-single-core feature. 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 */ }
}
Use the complete Cortex-M listing to inspect the no_std entry point, global LlffHeap, MaybeUninit backing store, unsafe initialization, and post-initialization allocations. section 7.2.2
Heap use remains an explicit trade-off. Predictable firmware rarely suffers meaningful fragmentation, while unpredictable allocation and freeing over long uptimes may justify TlsfHeap or buddy_system_allocator. Allocation failure normally reaches the panic handler; try_reserve can return a Result when recovery matters. heapless or arrayvec avoid the heap with fixed-capacity storage, while tinyvec and smallvec still require an allocator for overflow. section 7.2.5 section 7.5
