Rudeus
Rudeus

Reputation: 43

Rust variable lifetime and Security

I am having trouble understanding what is Rust protecting this program from:

fn foo() -> &i32 { 
    let x: i32 = 0;
    &x
}

fn main () {
    let p = foo();
    *p = 42 ; // attempt to store 42 at address p => error!
}

Why is there an error ? I understand that it is caused by local variable lifetime, what I don't understand is what common vulnerability is it protecting from ?

Is this system adopted by Rust made to protect against Use-after-free ? How is the C equivalent of this program Vulnerable ?

Upvotes: 1

Views: 70

Answers (1)

Tyler Aldrich
Tyler Aldrich

Reputation: 416

In your example, x is Dropped (https://doc.rust-lang.org/std/ops/trait.Drop.html) at the end of the function foo.

fn foo() -> &i32 { 
    let x: i32 = 0;
    &x
} // <-- `x` is dropped (or freed) at this point

fn main () {
    let p = foo(); <-- `p` would be a pointer to an area of memory that has been freed if the compiler allowed this
    *p = 42 ; <-- this would set some arbitrary memory address to 42 if it was allowed
}

This is protecting you from assigning a value to a reference that no longer points to a valid memory location.

Upvotes: 2

Related Questions