Memory allocation sets aside space for a value. A welcome program, for example, needs somewhere to store a visitor’s name before it can print “Welcome {name}.” When the value is no longer needed, deallocation makes that space available for reuse; Rust calls this cleanup *dropping* a value. section 2.2
Where a value lives matters. The stack holds values associated with active function calls, has a relatively small size limit, and adds or removes values at its top. The heap accommodates larger values and values whose size is not known until the program runs, such as strings and arrays. Heap storage is also called dynamic memory. section 2.2
Who frees the name?
In the welcome example, one version calls `free(name)` after `welcome(name)` returns; another puts `free(name)` inside `welcome`. Both make cleanup explicit, but place responsibility in different parts of the program. Rust’s drop terminology addresses the same need to stop retaining unused values. section 2.2
Allocation also becomes an interface task when a host calls a WebAssembly module. Wasm memory is a resizable buffer of raw bytes, and Wasm has no string primitive. To pass data, the host and module must agree how to allocate it and interpret it: obtain a location, write the input, run the function, then read the result. This is lower-level work than most application code requires. section 10.6
Listing 10.33 [paper_search|book_search]/src/main.rs: Allocating function
use std::os::raw::{c_void, c_int};
use std::mem;
#[no_mangle]
pub extern fn allocate(size: usize) -> *mut c_void {
let mut buffer = Vec::with_capacity(size); #1
let pointer = buffer.as_mut_ptr(); #2
mem::forget(buffer); #3
pointer as *mut c_void #4
}
The exported Rust `allocate(size)` function reserves capacity in a `Vec`, obtains its pointer, calls `mem::forget(buffer)`, and returns the pointer to its caller. section 10.6
Rust offers control over allocations when performance calls for it, without making every program start at this low level. Controlling allocations can produce speedups, but the value of doing so depends on the task. section 1.2










