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
