From ce198412490d8e86858db5c91b8128c4b1bc6a43 Mon Sep 17 00:00:00 2001 From: gendx Date: Thu, 9 Feb 2023 06:47:15 +0000 Subject: [PATCH] Add highly-unsafe speaker notes to inspect the memory layout of string. (#341) --- src/memory-management/stack.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/memory-management/stack.md b/src/memory-management/stack.md index ad06707b..bf925497 100644 --- a/src/memory-management/stack.md +++ b/src/memory-management/stack.md @@ -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}"); + } +} +``` + [System Allocator]: https://doc.rust-lang.org/std/alloc/struct.System.html