Step into the Rustacean’s Den 馃

Memory Allocation in Rust: Box, Vec, and the Global Allocator

This post explores how Rust manages memory through Box, Vec, and the global allocator, uncovering what really happens under the hood. Box and Vec Memory Allocation Before diving into implementation details, let鈥檚 first understand how Box and Vec internally use allocators. Box Box is the simplest smart pointer in Rust. It allocates a value on the heap while making ownership explicit and safe. Under the hood, though, Box is more complex than the Box<T> we usually write. Here鈥檚 the actual definition: ...

September 18, 2025 路 17 min 路 3435 words 路 Mns0327

Rust: How the Compiler Manages Lifetimes

Most people just use lifetimes without understanding how they are implemented under the hood. So I decided to dig into the compiled binary to see how Rust actually manages lifetimes at the machine level. The String Struct Layout Before diving into the assembly, it helps to recall how Rust represents a String internally. A String is essentially a wrapper around a Vec<u8>, which in turn manages a heap-allocated buffer: Field Description ptr Pointer to the heap-allocated buffer cap Capacity (number of bytes the buffer can hold without reallocating) len Current length (number of bytes used) alloc/src/string.rs alloc/src/vec/mod.rs alloc/src/raw_vec/mod.rs Move value In Rust, ownership ensures that when a value is passed to a function by move, the caller loses access to it. This guarantees that memory can be safely freed once the function finishes. Unlike in C, where the programmer decides when to free memory, Rust enforces this through the type system. ...

September 11, 2025 路 6 min 路 1165 words 路 Mns0327