diff --git a/src/memory-management/manual.md b/src/memory-management/manual.md index 069ca94a..90767ec8 100644 --- a/src/memory-management/manual.md +++ b/src/memory-management/manual.md @@ -2,6 +2,8 @@ You allocate and deallocate heap memory yourself. +If not done with care, this can lead to crashes, bugs, security vulnerabilities, and memory leaks. + ## C Example You must call `free` on every pointer you allocate with `malloc`: diff --git a/src/memory-management/rust.md b/src/memory-management/rust.md index e75f8a4b..cb18e80b 100644 --- a/src/memory-management/rust.md +++ b/src/memory-management/rust.md @@ -3,7 +3,22 @@ Memory management in Rust is a mix: * Safe and correct like Java, but without a garbage collector. +* Depending on which abstraction (or combonation of abstractions) you choose, can be a single unique pointer, reference counted, or atomically reference counted. * Scope-based like C++, but the compiler enforces full adherence. -* Has no runtime overhead like in C and C++. +* A Rust user can choose the right abstraction for the situation, some even have no cost at runtime like C. It achieves this by modeling _ownership_ explicitly. + +
+ +* If asked how at this point, you can mention that in Rust this is usually handled by RAII wrapper types such as [Box], [Vec], [Rc], or [Arc]. These encapsulate ownership and memory allocation via various means, and prevent the potential errors in C. + +* You may be asked about destructors here, the [Drop] trait is the Rust equivalent. + +
+ +[Box]: https://doc.rust-lang.org/std/boxed/struct.Box.html +[Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html +[Rc]: https://doc.rust-lang.org/std/rc/struct.Rc.html +[Arc]: https://doc.rust-lang.org/std/sync/struct.Arc.html +[Drop]: https://doc.rust-lang.org/std/ops/trait.Drop.html diff --git a/src/memory-management/stack.md b/src/memory-management/stack.md index b1b1dbd0..ad06707b 100644 --- a/src/memory-management/stack.md +++ b/src/memory-management/stack.md @@ -22,3 +22,14 @@ fn main() { : : `- - - - - - - - - - - - - - - -' `- - - - - - - - - - - - - -' ``` + +
+ +* 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] + +
+ +[System Allocator]: https://doc.rust-lang.org/std/alloc/struct.System.html +[Allocator API]: https://doc.rust-lang.org/std/alloc/index.html