Ownership in Assembly
Ownership is the headline feature of Rust. Every value has one owner; when that owner falls out of scope, the value is dropped. You'd expect runtime bookkeeping for that. There isn't any. This lesson cracks open the assembly output to show that ownership is policed entirely at compile time — the only cleanup code that ships is the same RAII machinery a C++ destructor would emit.
Moves in Rust: What Actually Happens
In Rust, assigning one variable to another "moves" the value:
fn main() { let s1 = String::from("hello"); let s2 = s1; // s1 is moved to s2; s1 is now invalid println!("{}", s2);}What does the move compile to?
; rustc 1.97, x86-64 Linux, -C opt-level=0 (symbol name shortened); A String is three 8-byte words: capacity, pointer, length = 24 bytes. call <String as From<&str>>::from ; builds s1 at [rsp+8]
; let s2 = s1: copy all 24 bytes to [rsp+32] mov rax, qword ptr [rsp + 24] ; third word (length) mov qword ptr [rsp + 48], rax movups xmm0, xmmword ptr [rsp + 8] ; first two words (capacity, pointer) movaps xmmword ptr [rsp + 32], xmm0Rust doesn't promise the order of a String's fields. The current standard library happens to store capacity, pointer, length, and a different release could reorder them, so never write code that depends on it.
The move is just a 24-byte memcpy. No ownership tag flipped, no refcount touched. The compiler copies the bytes and then never emits another instruction that reads s1. The "invalidation" lives entirely in the type checker — it refuses to compile code that uses s1 after the move. At the machine-code layer, there's no fingerprint of the transfer at all.
You will spot one extra in the unoptimised listing: a landing pad. If anything between creating s2 and the end of scope panics, unwinding jumps to a small block that drops s2 and calls _Unwind_Resume. That's the same table-driven unwinding C++ uses to run destructors during an exception, and it sits off the normal path; with panic = "abort" it disappears.
At the machine level, a Rust move is a plain C memcpy. The split happens in the compiler: Rust refuses to let you touch the source again, whereas C will happily hand you a use-after-move footgun. Safety here is the type checker doing its job, not a runtime watchdog.
Drop Glue: Compiler-Inserted Cleanup
When a value goes out of scope, the compiler inserts a "drop" call:
fn example() { let v = vec![1, 2, 3]; // ... use v ...} // v is dropped here: Vec's drop implementation frees the heap bufferexample: push rbx sub rsp, 24
; Create vec![1, 2, 3] ; ... (allocates heap buffer, stores [1, 2, 3]) ...
; Use v...
; Drop v (compiler-inserted): lea rdi, [rsp] ; Pointer to the Vec on stack call core::ptr::drop_in_place<alloc::vec::Vec<i32>> ; This eventually calls: dealloc(v.ptr, v.capacity * sizeof(i32))
add rsp, 24 pop rbx retdrop_in_place is what the Rust folk call "drop glue" — a per-type cleanup function the compiler generates on demand. Vec<i32> releases its heap buffer; String releases its UTF-8 buffer; a plain i32 or (f64, f64) has empty glue that the optimiser deletes outright.
Owned vs Borrowed Parameters
Compare passing by value (ownership handoff) against by reference (borrow):
fn take_ownership(s: String) { println!("{}", s);} // s is dropped here
fn borrow(s: &String) { println!("{}", s);} // Nothing to drop; s is a reference; take_ownership: receives String by value (24 bytes on stack or in registers)take_ownership: ; rdi = pointer to the 24-byte String, which this function now owns ; (Rust passes anything bigger than two registers indirectly) ; ... print the string ... ; Drop the String: call core::ptr::drop_in_place<alloc::string::String> ret
; borrow: receives &String (just an 8-byte pointer)borrow: ; rdi = pointer to the String ; ... print the string through the reference ... ; No drop! The caller still owns the String retAt the assembly level, the difference is:
- Owned: receives the String's 24 bytes (via a pointer to them) and is responsible for dropping it
- Borrowed: receives a pointer (8 bytes), does not drop anything
The borrow checker's guarantees — references can't outlive their data, mutable aliases can't coexist — are checked entirely at compile time. The assembly for a &String is the same handful of bytes you'd see for a raw C pointer. No runtime checks. No refcounting.
Copy Types vs Move Types
Types that implement Copy (integers, floats, bools) are duplicated instead of moved:
fn main() { let x: i32 = 42; let y = x; // Copy, not move - both x and y are valid println!("{} {}", x, y);}mov DWORD PTR [rbp-4], 42 ; x = 42 mov eax, DWORD PTR [rbp-4] mov DWORD PTR [rbp-8], eax ; y = x (just a copy) ; Both x and y remain accessibleFor Copy types, Rust and C produce the same single mov. The Copy trait is purely a compile-time marker — it tells the compiler "byte-for-byte duplication is fine for this type." Nothing leaks into the generated code.
Optimized Moves: The Compiler Is Smart
Crank the optimiser up and many moves vanish entirely:
fn create_string() -> String { String::from("hello")}
fn main() { let s = create_string(); println!("{}", s);}With optimisation, the String is built straight into the caller's memory. Unlike C++17, which guarantees copy elision in this case, Rust makes no promise here. It falls out of the calling convention, which returns a large value through a hidden pointer (the "sret" argument), plus LLVM deleting the temporary. In practice you get this:
create_string: ; rdi = hidden pointer to caller's memory for the result ; Constructs the String directly in the caller's stack frame ; (rustc 1.97 -O writes the fields in this order) mov QWORD PTR [rdi], 5 ; Write capacity mov QWORD PTR [rdi+8], rax ; Write pointer to the heap bytes mov QWORD PTR [rdi+16], 5 ; Write length mov rax, rdi ; Return the pointer ret
main: sub rsp, 24 lea rdi, [rsp] ; Pass address of our local String call create_string ; String constructed directly here ; No move necessary!Conditional Drops
If a value might or might not have been moved by the time the function returns, the compiler keeps a "drop flag" — a tiny boolean that decides whether to call drop on the way out:
fn example(condition: bool) { let s = String::from("hello"); if condition { drop(s); // Explicit drop } // At the end of the function, should s be dropped again? // Only if the if-branch was NOT taken!}example: ; ... create s ... mov BYTE PTR [rbp-1], 1 ; Drop flag = true (needs dropping)
test dil, dil ; Check condition je .skip_early_drop
; Early drop: lea rdi, [rbp-32] call core::ptr::drop_in_place<alloc::string::String> mov BYTE PTR [rbp-1], 0 ; Drop flag = false (already dropped)
.skip_early_drop: ; End of function: conditional drop cmp BYTE PTR [rbp-1], 0 je .no_drop lea rdi, [rbp-32] call core::ptr::drop_in_place<alloc::string::String>.no_drop: retThe drop flag is a single byte tracking "still needs dropping?". This is the rare corner where ownership leaks into runtime: one byte and a conditional. With aggressive optimisation, the compiler usually shoves the flag away by splitting paths so every branch has a statically known drop state.
Comparing to C and C++
| Operation | Rust | C | C++ |
|---|---|---|---|
| Move a String | memcpy 24 bytes | N/A (manual) | Move constructor (copy the fields, then reset the source) |
| Drop a String | call dealloc | Manual free() | Destructor (same as Rust) |
| Borrow a String | Pass 8-byte pointer | Pass pointer | Pass pointer or reference |
| Copy an int | mov instruction | mov instruction | mov instruction |
| Double-free prevention | Compile error | Undefined behaviour (often an allocator abort, sometimes silent heap corruption) | Use smart pointers |
That last row is the one to see in machine code. Below is a C function that frees the same pointer twice, next to what clang -O2 actually emits for x86-64 (only the string constant is rewritten in hex). Hover a line to match source to assembly. Nothing in the output hints at a problem: the second free is just another call, which the compiler even turned into a tail-call jmp. Whatever happens next is up to the allocator at run time.
A double free in C, compiled
x86-64Hover over code lines or mapping badges to see correspondences
The Rust version, let s = String::from("hello"); drop(s); drop(s);, never gets as far as generating code. The second drop(s) is rejected with error E0382, use of moved value.
Rust's ownership system emits the same assembly as careful C++ wrapped in unique_ptr — and throws in compile-time guarantees that vaporise whole bug families on top. The zero-cost abstraction line isn't marketing; ownership lives in the type system and nowhere else by the time you read the disassembly.