6.5 The String
Type and Memory Allocation
6.5.1 Stack vs. Heap Allocation
- Stack Allocation: Used for fixed-size data known at compile time; fast but limited in capacity.
- Heap Allocation: Used for dynamically sized or longer-lived data; allocation is slower and must be managed.
6.5.2 The Structure of a String
A Rust String
contains:
- A pointer to the heap-allocated UTF-8 data,
- A length (current number of bytes),
- A capacity (total allocated size in bytes).
This pointer/length/capacity trio sits on the stack, while the string’s contents reside on the heap. When the String
leaves its scope, Rust automatically frees its heap buffer.
6.5.3 How Strings Grow
When you add data to a String
, Rust may have to reallocate the underlying buffer. Commonly, it doubles the existing capacity to minimize frequent allocations.
6.5.4 String Literals
String literals of type &'static str
are stored in the read-only portion of the compiled binary:
#![allow(unused)] fn main() { let s: &str = "hello"; }
Similarly, in C:
const char *s = "hello";
These literals are loaded at program startup and stay valid throughout the program’s execution.