1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-12-24 07:19:47 +02:00
Files
comprehensive-rust/src/memory-management/stack.md
2023-01-12 11:51:37 +01:00

1.3 KiB

Stack Memory

Creating a String puts fixed-sized data on the stack and dynamically sized data on the heap:

fn main() {
    let s1 = String::from("Hello");
}
 Stack                             Heap
.- - - - - - - - - - - - - -.     .- - - - - - - - - - - - - - - -.
:                           :     :                               :
:    s1                     :     :                               :
:   +-----------+-------+   :     :   +----+----+----+----+----+  :
:   | ptr       |   o---+---+-----+-->| H  | e  | l  | l  | o  |  :
:   | len       |     5 |   :     :   +----+----+----+----+----+  :
:   | capacity  |     5 |   :     :                               :
:   +-----------+-------+   :     :                               :
:                           :     `- - - - - - - - - - - - - - - -'
`- - - - - - - - - - - - - -'
  • Mention that a String is backed by a Vec, so it has a capacity and length and can grow if mutable via reallocation on the heap.

  • If students ask about it, you can mention that the underlying memory is heap allocated using the System Allocator and custom allocators can be implemented using the Allocator API