alloc

To use alloc you must implement a global (heap) allocator.

  1. #![no_main]
  2. #![no_std]
  3. extern crate alloc;
  4. extern crate panic_halt as _;
  5. use alloc::string::ToString;
  6. use alloc::vec::Vec;
  7. use buddy_system_allocator::LockedHeap;
  8. #[global_allocator]
  9. static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();
  10. static mut HEAP: [u8; 65536] = [0; 65536];
  11. pub fn entry() {
  12.     // SAFETY: `HEAP` is only used here and `entry` is only called once.
  13.     unsafe {
  14.         // Give the allocator some memory to allocate.
  15.         HEAP_ALLOCATOR.lock().init(HEAP.as_mut_ptr() as usize, HEAP.len());
  16.     }
  17.     // Now we can do things that require heap allocation.
  18.     let mut v = Vec::new();
  19.     v.push("A string".to_string());
  20. }
  • buddy_system_allocator is a third-party crate implementing a basic buddy system allocator. Other crates are available, or you can write your own or hook into your existing allocator.
  • The const parameter of LockedHeap is the max order of the allocator; i.e. in this case it can allocate regions of up to 2**32 bytes.
  • If any crate in your dependency tree depends on alloc then you must have exactly one global allocator defined in your binary. Usually this is done in the top-level binary crate.
  • extern crate panic_halt as _ is necessary to ensure that the panic_halt crate is linked in so we get its panic handler.
  • This example will build but not run, as it doesn’t have an entry point.