# [−] [src] Module cortex_m_quickstart::examples::_6_allocator

How to use the heap and a dynamic memory allocator

This example depends on the alloc-cortex-m crate so you'll have to add it to your Cargo.toml:

    # or edit the Cargo.toml file manually
    $ cargo add alloc-cortex-m

    #![feature(alloc)]
    #![feature(global_allocator)]
    #![feature(lang_items)]
    #![no_main]
    #![no_std]

    // This is the allocator crate; you can use a different one
    extern crate alloc_cortex_m;
    #[macro_use]
    extern crate alloc;
    extern crate cortex_m;
    #[macro_use]
    extern crate cortex_m_rt as rt;
    extern crate cortex_m_semihosting as sh;
    extern crate panic_semihosting;

    use core::fmt::Write;

    use alloc_cortex_m::CortexMHeap;
    use cortex_m::asm;
    use rt::ExceptionFrame;
    use sh::hio;

    // this is the allocator the application will use
    #[global_allocator]
    static ALLOCATOR: CortexMHeap = CortexMHeap::empty();

    const HEAP_SIZE: usize = 1024; // in bytes

    entry!(main);

    fn main() -> ! {
        // Initialize the allocator BEFORE you use it
        unsafe { ALLOCATOR.init(rt::heap_start() as usize, HEAP_SIZE) }

        // Growable array allocated on the heap
        let xs = vec![0, 1, 2];

        let mut stdout = hio::hstdout().unwrap();
        writeln!(stdout, "{:?}", xs).unwrap();

        loop {}
    }

    // define what happens in an Out Of Memory (OOM) condition
    #[lang = "oom"]
    #[no_mangle]
    pub fn rust_oom() -> ! {
        asm::bkpt();

        loop {}
    }

    exception!(HardFault, hard_fault);

    fn hard_fault(ef: &ExceptionFrame) -> ! {
        panic!("HardFault at {:#?}", ef);
    }

    exception!(*, default_handler);

    fn default_handler(irqn: i16) {
        panic!("Unhandled exception (IRQn = {})", irqn);
    }

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)