The heap is an optional region of RAM for dynamically allocated data. It is useful when a buffer’s size or a collection’s lifetime cannot be known at compile time. Unlike static storage or the stack, the heap must be managed by an allocator. section 7.1.1
In embedded Rust, a no_std program has no default heap. To use heap-backed types such as Box, Vec, and String, add the alloc crate, reserve RAM for the heap, and install a global allocator. This is an explicit choice on a microcontroller, where RAM is limited and allocation can fail. section 1.3.1 section 7.0
To set up a heap in no_std:
- Choose an allocator implementation and mark its type with #[global_allocator]. section 7.2.1
- Choose the heap’s location and size. Reserve a static byte array and pass its address and length to the allocator at startup. section 7.2.1
- Use alloc-backed types once the allocator is configured. For Cortex-M, embedded-alloc is a standard choice; buddy_system_allocator is an alternative when fragmentation becomes a measurable problem. section 7.2 section 7.5
Plan for allocation failure. Fragmentation can cause an allocation to fail even when earlier allocations succeeded. The default failure path uses the program’s #[panic_handler]; where recovery is needed, try_reserve on Vec, String, and similar types returns a Result instead of panicking. section 7.0 section 7.5
#![no_std]
fn my_function() {
// Will not compile in pure `no_std` (no allocator available):
// let v: Vec<u8> = Vec::new();
// Use fixed-capacity data instead:
let mut buf: [u8; 32] = [0; 32];
let mut len = 0;
if len < buf.len() { buf[len] = 0xAB; len += 1; }
}
A fixed-size array can replace a Vec when the required capacity is known, avoiding the need for an allocator. section 1.3.1
For heap-free collections, heapless provides fixed-capacity containers that report overflow as a Result; arrayvec is a lighter-weight alternative. Hybrid containers such as smallvec and tinyvec use inline storage for common cases but still need a global allocator if they overflow to the heap. section 7.5










