rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.84k stars 353 forks source link

Clarify/Correct example of a dangling pointer in FFI/Passing-Strings #313

Open ImplOfAnImpl opened 2 years ago

ImplOfAnImpl commented 2 years ago

Hi.

I'm pretty new to Rust, so I may be missing something. But anyway :-)

So, ffi/passing-strings has this example:

fn report_error<S: Into<String>>(err: S) -> Result<(), std::ffi::NulError> {
    unsafe {
        // SAFETY: whoops, this contains a dangling pointer!
        seterr(std::ffi::CString::new(err.into())?.as_ptr());
    }
    Ok(())
}

I wonder, how can the pointer be dangling here, isn't the temporary that it's pointing to supposed to live until the end of the entire statement? I.e. the call to seterr should be completed before it's dropped.

Also, there was a review comment that suggested rewording this example completely, so that it would instead discourage constructing a temporary and obtaining a pointer to it in a let-statement. It seems that the comment's author also considered the example to be incorrect.