1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-25 08:53:01 +02:00

stackheap notes

This commit is contained in:
Brandon Pollack 2023-01-12 11:12:53 +09:00
parent bee9cdab92
commit f750f75db6
3 changed files with 29 additions and 1 deletions

View File

@ -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`:

View File

@ -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.
<details>
* 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.
</details>
[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

View File

@ -22,3 +22,14 @@ fn main() {
: : `- - - - - - - - - - - - - - - -'
`- - - - - - - - - - - - - -'
```
<details>
* 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]
</details>
[System Allocator]: https://doc.rust-lang.org/std/alloc/struct.System.html
[Allocator Api]: https://doc.rust-lang.org/std/alloc/index.html