0
0
Rustprogramming~20 mins

Why smart pointers are needed in Rust - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Smart Pointer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use smart pointers instead of raw pointers in Rust?

Which reason best explains why Rust uses smart pointers like Box or Rc instead of raw pointers?

ASmart pointers allow direct access to hardware registers without safety checks.
BSmart pointers make the code run faster than raw pointers in all cases.
CSmart pointers automatically manage memory and prevent errors like double free or dangling pointers.
DSmart pointers are used only to make the syntax shorter and simpler.
Attempts:
2 left
💡 Hint

Think about what problems can happen if you manually manage memory with raw pointers.

Predict Output
intermediate
2:00remaining
Output of code using Box smart pointer

What is the output of this Rust code?

Rust
fn main() {
    let x = Box::new(10);
    println!("{}", *x + 5);
}
A15
B10
CBox(10) + 5
DCompilation error
Attempts:
2 left
💡 Hint

Remember that Box stores the value on the heap and you can access the value by dereferencing.

Predict Output
advanced
2:00remaining
What error occurs with raw pointer misuse?

What error will this Rust code produce?

Rust
fn main() {
    let mut x = 5;
    let r1 = &x as *const i32;
    let r2 = &mut x as *mut i32;
    unsafe {
        *r2 = 10;
        println!("{}", *r1);
    }
}
APrints 10 without error
BCompilation error due to mutable and immutable borrow
CRuntime undefined behavior due to raw pointer aliasing
DPrints 5 without error
Attempts:
2 left
💡 Hint

Raw pointers allow unsafe code but you must be careful with aliasing rules.

🧠 Conceptual
advanced
2:00remaining
Why does Rust prefer smart pointers over garbage collection?

Why does Rust use smart pointers like Rc and Arc instead of a garbage collector?

AGarbage collectors are faster and simpler, so Rust avoids them for performance reasons.
BSmart pointers give precise control over memory without runtime overhead of garbage collection.
CRust does not support dynamic memory allocation at all.
DSmart pointers automatically parallelize code execution.
Attempts:
2 left
💡 Hint

Think about how Rust manages memory without a background process cleaning unused data.

🚀 Application
expert
3:00remaining
How many strong references remain after cloning Rc?

Consider this Rust code using Rc smart pointer:

use std::rc::Rc;

fn main() {
    let a = Rc::new(5);
    let b = Rc::clone(&a);
    let c = Rc::clone(&b);
    drop(b);
    println!("{}", Rc::strong_count(&a));
}

What number will be printed?

ACompilation error
B3
C1
D2
Attempts:
2 left
💡 Hint

Count how many Rc pointers are alive after dropping one.