std-function
Allocate and initialize a single value
Direct allocation returns raw storage, not a constructed Rust value. Handle allocation failure before access. Initialize the storage with a write, read only the initialized value, and release the allocation with the same layout. This narrowly scoped example uses a Copy value and no fallible operations between initialization and deallocation. Expected stdout (not executed): value=73 Common mistake: Reading newly allocated storage before initializing it.
Formal Syntax & Structure
rust syntaxrust
unsafe { std::alloc::alloc(layout) }Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::alloc::{alloc, dealloc, handle_alloc_error, Layout}; let layout = Layout::new::<u32>(); // SAFETY: u32 has nonzero size and layout describes its storage. let raw = unsafe { alloc(layout) }; if raw.is_null() { handle_alloc_error(layout); } let ptr = raw.cast::<u32>(); // SAFETY: successful allocation is suitably aligned and large enough; exclusively owned. let value = unsafe { ptr.write(73); let value = ptr.read(); dealloc(raw, layout); value }; println!("value={value}");}