Bird
Raised Fist0
Rustprogramming~10 mins

Ownership with smart pointers in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Ownership with smart pointers
Create smart pointer
↓
Pointer owns data
↓
Use data via pointer
↓
Pointer goes out of scope
↓
Data is dropped automatically
This flow shows how a smart pointer owns data, allows safe use, and cleans up automatically when it goes out of scope.
Execution Sample
Rust
fn main() {
    let s = Box::new(String::from("hello"));
    println!("{}", s);
}
Creates a Box smart pointer owning a String, prints it, then automatically frees memory when done.
Execution Table
StepActionPointer StateData StateOutput
1Create Box smart pointer ss owns String("hello")String("hello") allocated on heap
2Print value via ss owns String("hello")String("hello") accessiblehello
3End of scope, s droppeds dropped, no longer validString("hello") memory freed
💡 Pointer s goes out of scope, Rust automatically frees the owned data.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3 (end)
suninitializedBox owning String("hello")Box owning String("hello")dropped (no longer valid)
String dataunallocatedallocated on heapaccessible via sfreed
Key Moments - 3 Insights
Why does the String data get freed automatically without calling drop()?
Because the Box smart pointer owns the data and Rust’s ownership rules automatically call drop when s goes out of scope (see execution_table step 3).
Can we use s after it is dropped at the end of main?
No, after step 3 in execution_table, s is dropped and no longer valid, so using it would cause a compile error.
Why is the String data stored on the heap and not the stack?
Box allocates data on the heap to allow ownership and dynamic size, while the pointer s itself is on the stack (see execution_table step 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the output when printing s?
Ahello
BBox pointer address
CString data is empty
DCompilation error
💡 Hint
Check the Output column at step 2 in execution_table.
At which step does the Box pointer s get dropped and free the String data?
AStep 1
BStep 3
CStep 2
DNever dropped
💡 Hint
Look at the Action and Pointer State columns in execution_table step 3.
If we tried to use s after step 3, what would happen?
AIt would print the String again
BProgram crashes at runtime
CRust compiler error for use after drop
Ds would be reinitialized automatically
💡 Hint
Refer to variable_tracker showing s is dropped after step 3.
Concept Snapshot
Ownership with smart pointers in Rust:
- Smart pointers like Box own heap data
- Data is accessed safely via the pointer
- When pointer goes out of scope, data is freed automatically
- Prevents manual memory errors
- Enables safe, automatic cleanup
Full Transcript
This example shows how Rust uses smart pointers like Box to own data on the heap. When we create s as Box::new(String::from("hello")), s owns the String data. We can use s to access and print the string safely. When s goes out of scope at the end of main, Rust automatically calls drop to free the heap memory. This automatic cleanup prevents memory leaks and errors. Trying to use s after it is dropped would cause a compile-time error. The variable tracker shows s owning the data after creation, and being dropped at the end. The execution table traces each step: creation, usage, and cleanup. This flow helps beginners understand ownership and automatic memory management with smart pointers in Rust.

Practice

(1/5)
1. Which smart pointer in Rust allows multiple parts of your program to own the same data safely?
easy
A. RefCell
B. Box
C. Rc
D. Arc

Solution

  1. Step 1: Understand ownership types

    Box provides unique ownership, Rc allows shared ownership in single-threaded contexts, RefCell allows interior mutability, and Arc is for shared ownership across threads.
  2. Step 2: Identify shared ownership in single-threaded code

    Rc is the smart pointer designed for multiple owners in single-threaded programs.
  3. Final Answer:

    Rc -> Option C
  4. Quick Check:

    Shared ownership = Rc [OK]
Hint: Shared ownership in single-threaded Rust uses Rc [OK]
Common Mistakes:
  • Confusing Box with shared ownership
  • Thinking RefCell shares ownership
  • Mixing Arc with single-threaded Rc
2. Which of the following is the correct way to create a Box smart pointer holding the integer 10?
easy
A. let b = Box::new(10);
B. let b = Box(10);
C. let b = new Box(10);
D. let b = Box::create(10);

Solution

  1. Step 1: Recall Box creation syntax

    The correct way to create a Box is using Box::new(value).
  2. Step 2: Check each option

    let b = Box::new(10); uses Box::new(10), which is correct. Options A, C, and D use invalid syntax.
  3. Final Answer:

    let b = Box::new(10); -> Option A
  4. Quick Check:

    Box creation = Box::new(value) [OK]
Hint: Use Box::new(value) to create a Box smart pointer [OK]
Common Mistakes:
  • Using Box(10) instead of Box::new(10)
  • Trying new Box(10) like other languages
  • Using non-existent Box::create method
3. What will be the output of this Rust code?
use std::rc::Rc;

let a = Rc::new(5);
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a));
medium
A. 1
B. 2
C. 5
D. Compilation error

Solution

  1. Step 1: Understand Rc cloning

    Cloning an Rc pointer increases the reference count but does not clone the data.
  2. Step 2: Count strong references

    Initially, a has a count of 1. After b = Rc::clone(&a), the count becomes 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Rc clone increments count = 2 [OK]
Hint: Rc::clone increases strong_count by 1 [OK]
Common Mistakes:
  • Thinking Rc::clone copies data
  • Expecting count to remain 1
  • Confusing Rc with Box ownership
4. Identify the error in this Rust code using RefCell:
use std::cell::RefCell;

let data = RefCell::new(10);
let r1 = data.borrow_mut();
let r2 = data.borrow_mut();
println!("{} {}", r1, r2);
medium
A. Cannot borrow mutably twice at the same time
B. RefCell cannot hold integers
C. Missing semicolon after borrow_mut()
D. Cannot print RefCell values directly

Solution

  1. Step 1: Understand RefCell borrowing rules

    RefCell allows mutable borrowing at runtime but only one mutable borrow at a time.
  2. Step 2: Analyze the code

    The code tries to create two mutable borrows r1 and r2 simultaneously, which causes a runtime panic.
  3. Final Answer:

    Cannot borrow mutably twice at the same time -> Option A
  4. Quick Check:

    RefCell mutable borrow rule = one at a time [OK]
Hint: Only one mutable borrow allowed with RefCell at once [OK]
Common Mistakes:
  • Thinking RefCell forbids integers
  • Assuming multiple mutable borrows are allowed
  • Confusing compile-time and runtime borrow checks
5. You want to create a tree structure where each node can have multiple children and each child can access its parent. Which combination of smart pointers is best to avoid ownership errors?
hard
A. Use Weak for children and Box for parent references
B. Use Box for both children and parent references
C. Use RefCell for children and Rc for parent references
D. Use Rc for children and Weak for parent references

Solution

  1. Step 1: Understand ownership in tree structures

    Children own their data, so Rc is used for shared ownership of children nodes.
  2. Step 2: Avoid reference cycles

    Parents are referenced by children, but to avoid cycles, parents should be referenced with Weak pointers.
  3. Step 3: Combine smart pointers correctly

    Using Rc for children and Weak for parents prevents memory leaks and ownership errors.
  4. Final Answer:

    Use Rc for children and Weak for parent references -> Option D
  5. Quick Check:

    Tree ownership = Rc children + Weak parents [OK]
Hint: Use Weak for back references to avoid cycles [OK]
Common Mistakes:
  • Using Box for parent causes ownership conflicts
  • Using Rc for parents causes reference cycles
  • Ignoring Weak pointers to break cycles
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard