liveBook · Manning

Memory allocation

As explained in Code Like a Pro in Rust

Memory allocation is the process of reserving memory regions for data during program execution.

Memory allocation reserves space for data during execution. Rust’s core data structures manage allocation and deallocation, while custom allocators offer more control when an application needs it. section 5.0

The heap supports dynamic allocation, including resizable data and data whose size is known only at runtime. The stack is thread-local and follows last-in, first-out order around function calls. Memory-constrained systems can also run without a heap. section 5.1

Listing 5.1 Code showing heap-allocated values
let heap_integer = Box::new(1);
let heap_integer_vec = vec![0; 100];
let heap_string = String::from("heap string");    #1

Box, Vec, and String provide common ways to allocate data on the heap. section 5.1

String owns mutable heap-allocated UTF-8 data; a &str borrows a UTF-8 slice and can refer to heap-allocated data. Vec stores elements in contiguous blocks and allocates lazily, with capacity controlling the allocation size. section 4.1.1 section 11.2

For fixed-size data structures without dynamic allocation, consider the heapless crate. When dynamic allocation is needed, a global allocator can be implemented with GlobalAlloc; alloc-cortex-m provides a heap allocator for Cortex-M platforms. section 2.12.1

A custom Allocator requires allocate and deallocate methods. Its default grow and shrink implementations allocate new memory, copy the data, and release the old allocation; overriding them may offer optimization opportunities. Allocator code involves unsafe operations, and portable implementations must handle both size and alignment from Layout. section 5.8.1

Listing 5.11 Code for a pass-through allocator
#![feature(allocator_api)]

use std::alloc::{AllocError, Allocator, Global, Layout};
use std::ptr::NonNull;

pub struct PassThruAllocator;

unsafe impl Allocator for PassThruAllocator {
 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
     Global.allocate(layout)
 }
 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
     Global.deallocate(ptr, layout)
 }
}

This pass-through allocator delegates allocation and deallocation to the global allocator. The allocator API example requires nightly Rust. section 5.8.1

fn main() {
    let mut custom_alloc_vec: Vec<i32, _> =
        Vec::with_capacity_in(10, BasicAllocator);      #1
    for i in 0..10 {
        custom_alloc_vec.push(i as i32 + 1);
    }
    println!("custom_alloc_vec={:?}", custom_alloc_vec);
}

A Vec can be created with a custom allocator and an initial capacity. section 5.8.1

How Code Like a Pro in Rust covers it

How deep it goes
Explains heap and stack behavior, Vec allocation, and custom allocator methods, including default resizing and layout requirements.
Examples
Shows heap-allocated Box, Vec, and String values, plus a pass-through allocator used with Vec.
What you can do after
Build a custom allocator and use it with Vec, or choose fixed-size structures when dynamic allocation is unnecessary.
How it connects
Connects allocation to ownership, smart pointers, reference counting, and data structures.

Also explained in

Compare how 13 books explain memory allocation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.