Rust Reference ยท Smart Pointers and Memory
The std::alloc module
Reference for Rust std::alloc: Layout, alloc, dealloc, realloc, alloc_zeroed, handle_alloc_error, GlobalAlloc and #[global_allocator] with examples.
std::alloc is the lowest-level interface to heap memory in Rust. Types such as Box, Vec and String call it for you. It offers Layout, a description of the size and alignment of a block, the functions alloc, alloc_zeroed, realloc and dealloc, and the GlobalAlloc trait that lets you replace the allocator for the whole program.
You use it to build your own containers, arenas, or to count and limit allocations. The functions are unsafe because the compiler cannot check that you free what you allocate, with the same layout, exactly once.
use std::alloc::{alloc, dealloc, Layout}; let layout = Layout::new::<u64>(); let p = unsafe { alloc(layout) } as *mut u64; unsafe { p.write(5); dealloc(p as *mut u8, layout) };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub unsafe fn alloc(layout: Layout) -> *mut u8; pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8; pub unsafe fn dealloc(ptr: *mut u8, layout: Layout); pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8; pub fn handle_alloc_error(layout: Layout) -> !; impl Layout { pub const fn from_size_align(size: usize, align: usize) -> Result<Layout, LayoutError>; pub const fn new<T>() -> Layout; pub fn array<T>(n: usize) -> Result<Layout, LayoutError>; pub const fn size(&self) -> usize; pub const fn align(&self) -> usize; } pub unsafe trait GlobalAlloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8; unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout); // provided: alloc_zeroed, realloc }
| Item | Description |
|---|---|
Layout |
Size plus alignment (a power of two). from_size_align returns Err for a bad alignment or a size that overflows isize after rounding. |
alloc(layout) |
Returns a pointer, or null on failure. Size must not be zero. |
alloc_zeroed |
Same, with all bytes zero. |
dealloc(ptr, layout) |
Frees memory; layout must equal the one used to allocate. |
realloc(ptr, layout, new_size) |
Grows or shrinks; the old pointer is invalid afterwards (if non-null returned). |
handle_alloc_error |
Aborts (or panics, depending on configuration) after allocation failure. |
System |
The default platform allocator, usable for wrapping. |
Errors / edge cases. Allocating with a zero-size layout is undefined behavior; container code special-cases zero-sized types. Freeing a pointer with a different layout, twice, or one that did not come from the same allocator is undefined behavior. alloc returns null when memory runs out; Vec and Box call handle_alloc_error for you.
Usage notes
- Most code needs none of this. Use
Vec::with_capacity,Box::neworBox<[T]>instead. - A custom
#[global_allocator]must not allocate inside its own methods (it would recurse); use atomics, as above. GlobalAllocis a safe-to-use, unsafe-to-implement trait: your implementation must return aligned, non-overlapping memory and be thread-safe.- The 800 bytes for a
Vec<u64>of capacity 100 are deterministic, butprintln!and the standard library allocate too (for example the stdout buffer), so compare counters only around the region you care about and avoid exact equality checks on totals. - For memory profiling prefer a counting allocator in tests over guessing; for speed, swapping in a faster allocator (mimalloc, jemalloc) is a one-line
#[global_allocator], but those are crates and not available in this runner. - The unstable
Allocatortrait (per-collection allocators) is not on stable Rust.