Memory Layouts and Smart Pointers
2026-09-03
Segments (high to low):
Keep track of per-call state
Frame is popped when call returns
drop call when owner goes out of scopeUsed for
static items
'static lifetime (more on this soon)Data size/placement is set at compile time.
Representation in memory:
tagvalue)valueUsual advice: order fields by decreasing size to minimize alignment padding
u64 usually starts at an 8-byte boundary= value (as in Crepr macro makes it a specific integer typecode as u16 to get value (as is like a cast)Pretend this was not optimized to nothing.
What is the memory picture?
String is a struct with capacity, address, lengthFor a String:
The clone method (trait Clone) usually makes a deep copy
hello consumes s and clone (call drop at return)String::from(s) copies data from s. Why?Option<u16>? An Option<u32>?&T and &mut T&[T] and &mut [T]*const T and *mut T (unsafe)Box<T>: Owning pointerRc<T>: Reference counted smart pointerRefCell<T>: Run-time checked referencesString, Vec) use pointers internally.Box<T> is an owning pointer to a T on the heapDeref trait, * accesses contents
T methods directly on Box<T>& and &mut)rc is the strong reference count
rcArc (and Mutex) later in semesterp1 and p2 point to the same heap dataBox<T>)RefCell, enforce borrow safety at runtimex even though x is immutableWhat might memory look like for representing this?
Basic rules
… with some addenda for smart pointers
drop reference passed from caller while in callee!Passing out references seems dangerous!
Want to relate input and output references somehow.
&self)&self
&self (and return value) remain borrowed on return#[derive(Debug)]
struct Point2d(f64, f64);
fn borrow1(p: &Point2d) -> &f64 { return &p.0; }
fn get1(p: &Point2d) -> f64 { return p.0; }
fn change2(p: &mut Point2d) { p.1 = 1.0; }
fn main() {
let mut p = Point2d(0.0, 0.0);
//let x = borrow1(&p); // Compile error
let x = get1(&p); // This is OK
change2(&mut p);
println!("{x} {p:?}");
}'a is a lifetime parameterWhen returning a reference, can skip lifetime parameter if
&self in a methodOtherwise, need an explicit parameter.
What would you like to hear about from me
(course material or otherwise)?