allocator.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //! How to use the heap and a dynamic memory allocator
  2. //!
  3. //! This example depends on the alloc-cortex-m crate so you'll have to add it to your Cargo.toml:
  4. //!
  5. //! ``` text
  6. //! # or edit the Cargo.toml file manually
  7. //! $ cargo add alloc-cortex-m
  8. //! ```
  9. //!
  10. //! ---
  11. #![feature(alloc_error_handler)]
  12. #![no_main]
  13. #![no_std]
  14. extern crate alloc;
  15. use panic_halt as _;
  16. use self::alloc::vec;
  17. use core::alloc::Layout;
  18. use alloc_cortex_m::CortexMHeap;
  19. use cortex_m::asm;
  20. use cortex_m_rt::entry;
  21. use cortex_m_semihosting::{hprintln, debug};
  22. // this is the allocator the application will use
  23. #[global_allocator]
  24. static ALLOCATOR: CortexMHeap = CortexMHeap::empty();
  25. const HEAP_SIZE: usize = 1024; // in bytes
  26. #[entry]
  27. fn main() -> ! {
  28. // Initialize the allocator BEFORE you use it
  29. unsafe { ALLOCATOR.init(cortex_m_rt::heap_start() as usize, HEAP_SIZE) }
  30. // Growable array allocated on the heap
  31. let xs = vec![0, 1, 2];
  32. hprintln!("{:?}", xs).unwrap();
  33. // exit QEMU
  34. // NOTE do not run this on hardware; it can corrupt OpenOCD state
  35. debug::exit(debug::EXIT_SUCCESS);
  36. loop {}
  37. }
  38. // define what happens in an Out Of Memory (OOM) condition
  39. #[alloc_error_handler]
  40. fn alloc_error(_layout: Layout) -> ! {
  41. asm::bkpt();
  42. loop {}
  43. }