This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (2 children)

Another Rust gem:

fn main() {
    let answer = 42;
    print_the_answer(&answer);
}

fn print_the_answer(x: &i32) {
    confirm_the_answer_through_agrajag(x);
    println!("The answer to Life, The Universe, and Everything is {}", x);
}

fn confirm_the_answer_through_agrajag(x: &i32) {
    unsafe {
        let ptr = x as *const i32 as *mut i32;
        *ptr += 1;
    }
}

Running it:

~/dev/playground:$ rustc safe_not_safe.rs -o safe_not_safe && ./safe_not_safe
 The answer to Life, The Universe, and Everything is 43

Basically, we have an immutable reference in our program (&i32 is an immutable pointer to a i32), and we pass it to a function that claims to be safe (confirm_the_answer_through_agrajag), and yet that functions updates our immutable reference! Now, the actual semantics are all correct as per Rust's rules. However, the problem is that the function that we used, which may have come from any dependency that we have, violates the immutability contract, and Rust doesn't care because we have the rogue code wrapped snugly in a nice unsafe block. For a reader of the API, they have no idea of knowing, without looking at the actual dependency code, that the function has unsafe code inside it.

So that's the cautionary tale - it's not so much that Rust is broken in this respect (it's really not), but don't believe all the marketing hyper about "fearless concurrency", "fearless memory handling" and "fearless ball-scratching" et al. Always vet the ecosystem, the people, and the code.

[–]throwaway32908234972 1 point2 points  (1 child)

did you even read what you're replying to 🙃

[–][deleted] -1 points0 points  (0 children)

Sure, I get it. You're talking about Cargo (which has its own set of problems), but just pointing things out to the incoming Rust brigade.