No_std & custom allocator: How to create an array on the heap?

Just for fun and knowledge I am going completely barebones Rust for my arm MCU. No std, no other crates.

I am trying to hack up the equivalent of the vec struct so I can create arrays at runtime. The idea is that myVec will be unsafe, but all the rest of the code safe.

My problem is that it doesn't seem like it's possible to get the size of a generic parameter, so not sure how to find how much memory to allocate.

Any idea how vec actually overcomes that? I tried to have a look at the vec code but I got confused.


What you are looking for is this I think.

Just in case you don't know: your code can provide a custom allocator which allows you to use the collections that are provided by the std (You don't access them using std but alloc).
I would recommend searching for something along the lines "rust custom allocator", that should give you most relevant results and some examples.


Thanks @raidwas.

The alloc sounds great, however I am using the stable channel. And although alloc is stable, when I try to use it, it says I should be using alloc_error_handler:

#[alloc_error_handler]` function required, but not found

However alloc_error_handler is unstable. Am I doing something wrong?

I think using alloc as a binary crate without std is still unstable. It should be fine to use, but will require nightly and might change its interface in the future. Rust stabilized alloc use in libraries, so that more libraries could be no_std, but it hasn't been stabilized for the top-level binary crates yet.

Edit: to be clear, even if you use alloc in a library that isn't your final binary, you'll still get this error. It's writing a binary which has an (indirect) dependency on alloc but not on std which is unstable.

1 Like

Thanks @daboross. Makes sense

1 Like

Note: you also need to ensure that you have the correct alignment, you can use std::mem::align_of to get the alignment, or std::alloc::Layout to get both the size and alignment.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.