After Chs 5 and 6 (see the reading club post here), we get a capstone quiz that covers ownership along with struts and enums.

So, lets do the quiz together! If you’ve done it already, revisiting might still be very instructive! I certainly thought these questions were useful “revision”.


I’ll post a comment for each question with the answer, along with my own personal notes (and quotes from The Book if helpful), behind spoiler tags.

Feel free to try to answer in a comment before checking (if you dare). But the main point is to understand the point the question is making, so share any confusions/difficulties too, and of course any corrections of my comments/notes!.

  • maegul (he/they)@lemmy.mlOPM
    link
    fedilink
    English
    arrow-up
    1
    ·
    5 months ago

    Q5

    • Which programs would pass the compiler (presuming this function, from above, passes too) and possibly cause undefined behaviour?
    /// Gets the string out of an option if it exists,
    /// returning a default otherwise
    fn get_or_default(arg: &Option<String>) -> String {
        if arg.is_none() {
            return String::new();
        }
        let s = arg.unwrap();
        s.clone()
    }
    

    Options:

    • None of these programs
    // 1
    let opt = Some(String::from("Rust"));
    let s = get_or_default(&opt);
    println!("{}", s);
    
    // 2
    let opt = Some(String::from("Rust"));
    get_or_default(&opt);
    
    // 3
    let opt = Some(String::from("Rust"));
    get_or_default(&opt);
    println!("{:?}", opt);
    
    Answer
    • All programs (1, 2 and 3).

    • Once arg.unwrap() occurs, s takes ownership of the underlying String.

    • Once s “dies”, the String is deallocated.

    • But, opt, from before the call to get_or_default also owns the same String, and so once it “dies” and its memory is deallocated, a double-free will occur.

    • This actually threw me at first

    • My answer was program 3, as I figured that opt had to be used in some way for “undefined behaviour” to occur, as only then, did I figure, would the inappropriate memory be used resulting in an incorrect result

    • This is kinda wrong, though, because deallocation occurs once opt’s lifetime ends, which will cause a double-free. println prolongs the lifetime while in program 2 the lifetime of opt clearly ends, I suppose, causing the double-free.

      • I personally think this is completely ambiguous, and unless I’m missing something, these undefined behaviour questions easily suffer from these problems.