![](https://lemmy.ml/pictrs/image/898b2fe2-24e9-4d30-a911-2a9c149b673d.png)
![](https://lemmy.ml/pictrs/image/b5ded61a-ac07-413b-a2bc-3d7321eadde2.jpeg)
Q2
/// Makes a string to separate lines of text,
/// returning a default if the provided string is blank
fn make_separator(user_str: &str) -> &str {
if user_str == "" {
let default = "=".repeat(10);
&default
} else {
user_str
}
}
Normally if you try to compile this function, the compiler returns the following error:
error[E0515]: cannot return reference to local variable `default`
--> test.rs:6:9
|
6 | &default
| ^^^^^^^^ returns a reference to data owned by the current function
Assume that the compiler did NOT reject this function. Which (if any) of the following programs would (1) pass the compiler, and (2) possibly cause undefined behavior if executed? Check each program that satisfies both criteria, OR check “None of these programs” if none are satisfying.
- None of these programs
// 1
let s = make_separator("");
// 2
let s = make_separator("");
println!("{s}");
// 3
println!("{}", make_separator("Hello world!"));
Answer
- Slightly dodgy question, as the undefined behaviour first requires an empty string to be passed in to trigger the return of
&default
, which results in a dangling pointer being returned. Then, it’s any program that uses the returned reference (so printing will do the trick)
Context: First, the caller must pass an empty string to trigger the problematic if-condition. This returns a dangling pointer. Second, the caller must use the result of make_separator, e.g. via println.
Q1
/// Makes a string to separate lines of text, /// returning a default if the provided string is blank fn make_separator(user_str: &str) -> &str { if user_str == "" { let default = "=".repeat(10); &default } else { user_str } }
When compiling, what’s the best description of the compiler error?
Answer
Cannot return reference to a local variable
&default
isn’t allowed asdefault
is local to the function."=".repeat(10)
directly?String
(requires convertinguser_str
to aString
withto_string()
)