0 day streak
rust / expert
Snippet

Low-Level Memory Allocation with Custom Layouts

This snippet demonstrates how to manually manage heap memory using the standard library's raw allocation API. We construct a memory layout for an array of 4 u32 elements, allocate the uninitialized memory, write values using raw pointers, read them back, and then deallocate the memory block to prevent leaks.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use std::alloc::{alloc, dealloc, Layout};
fn main() {
unsafe {
let layout = Layout::array::<u32>(4).unwrap();
let ptr = alloc(layout) as *mut u32;
if ptr.is_null() {
panic!("Allocation failed");
}
for i in 0..4 {
ptr.add(i).write(i as u32 * 10);
}
for i in 0..4 {
let val = ptr.add(i).read();
assert_eq!(val, i as u32 * 10);
}
dealloc(ptr as *mut u8, layout);
}
}
Breakdown
1
Layout::array::<u32>(4).unwrap()
Calculates the size and alignment requirements for an array of four 32-bit unsigned integers.
2
alloc(layout)
Allocates a block of heap memory matching the specified layout, returning a raw *mut u8 pointer.
3
ptr.add(i).write(...)
Calculates the offset for the i-th element and writes the value directly to the uninitialized memory location.
4
dealloc(ptr as *mut u8, layout)
Releases the allocated block of memory back to the allocator, requiring the original pointer and layout.