Dynamic allocation reserves memory from a heap at runtime. It is useful when data size or lifetime cannot be known at compile time, such as a sensor buffer whose length varies or a client list that grows and shrinks. section 7.1.1
In embedded Rust, the heap is optional. A no_std program has no heap by default: the developer must reserve RAM for it and install an allocator. On a microcontroller with limited RAM, allocation can fail; fragmentation can make an allocation fail even if similar requests succeeded earlier. Allocator overhead, unpredictable timing, and power draw are also trade-offs. section 7.1.1 section 7.0
Figure 7.1 Memory regions of an embedded Rust program
Compare the heap with the stack and static memory regions in an embedded program. section 7.1.1
Rust's core crate provides language fundamentals without dynamic allocation. Heap-dependent types such as Box, Vec, and String are in alloc, which is not linked by default in a no_std build. Declare extern crate alloc at the crate root and provide a global allocator; without an allocator implementation, the program will not link. section 7.1.2
To enable a heap in no_std firmware:
- Choose an allocator implementation and mark its type with #[global_allocator]. section 7.2.1
- Choose the heap's location and size in RAM. Reserve a static byte array and pass its address and length to the allocator at startup. section 7.2.1
- Use alloc APIs such as Box::new or Vec::push, while accounting for allocation failure on a memory-constrained device. section 7.1.2 section 7.2.1
A buffer with a runtime size
A sensor buffer whose length depends on a reading can use heap allocation when its required size cannot be known at compile time. First consider whether a fixed-capacity container is sufficient: heapless and arrayvec offer heap-free alternatives, avoiding allocator complexity at the cost of a fixed capacity. section 7.1.1 section 7.0 section 7.1.2
Prefer core with stack or static storage by default. Use a heap when its flexibility solves a concrete problem that the available alternatives do not, and plan for its resource limits and failure behavior. section 7.1.2 section 7.1.1
