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



