1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-01-05 16:10:31 +02:00

Add highly-unsafe speaker notes to inspect the memory layout of string. (#341)

This commit is contained in:
gendx 2023-02-09 06:47:15 +00:00 committed by GitHub
parent 6df343736a
commit ce19841249
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -29,6 +29,23 @@ fn main() {
* 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]
* We can inspect the memory layout with `unsafe` code. However, you should point out that this is rightfully unsafe!
```rust,editable
fn main() {
let mut s1 = String::from("Hello");
s1.push(' ');
s1.push_str("world");
// DON'T DO THIS AT HOME! For educational purposes only.
// String provides no guarantees about its layout, so this could lead to
// undefined behavior.
unsafe {
let (capacity, ptr, len): (usize, usize, usize) = std::mem::transmute(s1);
println!("ptr = {ptr:#x}, len = {len}, capacity = {capacity}");
}
}
```
</details>
[System Allocator]: https://doc.rust-lang.org/std/alloc/struct.System.html