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
