5
Reading Club: The Book - Ownership Inventory Quiz no 1 [PROJECT]
(rust-book.cs.brown.edu)
A collaborative space for people to work together on learning Rust, learning about the Lemmy code base, discussing whatever confusions or difficulties we're having in these endeavours, and solving problems, including, hopefully, some contributions back to the Lemmy code base.
Rules TL;DR: Be nice, constructive, and focus on learning and working together on understanding Rust and Lemmy.
See also:
Thumbnail and banner generated by ChatGPT.
Q5
Options:
Answer
All programs (1, 2 and 3).
Once
arg.unwrap()occurs,stakes ownership of the underlyingString.Once
s"dies", theStringis deallocated.But,
opt, from before the call toget_or_defaultalso owns the sameString, and so once it "dies" and its memory is deallocated, adouble-freewill occur.This actually threw me at first
My answer was program
3, as I figured thatopthad 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 resultThis is kinda wrong, though, because deallocation occurs once
opt's lifetime ends, which will cause a double-free.printlnprolongs the lifetime while in program2the lifetime ofoptclearly ends, I suppose, causing the double-free.