There are two primary ways to initialize the heap:
1. Using the init! macro
This is the simplest method. It takes the static allocator instance and the desired heap size in bytes.
unsafe {
embedded_alloc::init!(HEAP, 1024);
}
2. Manual initialization
If you need to control exactly where the heap memory resides (e.g., using a specific static array), you can call .init() directly on the heap instance. This requires passing the raw pointer to the memory and the size.
use core::mem::MaybeUninit;
const HEAP_SIZE: usize = 1024;
static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
unsafe {
HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE)
}
#![no_std]
#![no_main]
extern crate alloc;
use cortex_m_rt::entry;
use embedded_alloc::LlffHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
#[entry]
fn main() -> ! {
// Method 1: Using the init! macro
unsafe {
embedded_alloc::init!(HEAP, 1024);
}
// Method 2: Manual initialization with specific memory
{
use core::mem::MaybeUninit;
const HEAP_SIZE: usize = 1024;
static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
unsafe { HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) }
}
loop { /* .. */ }
}