Playground
It's rather a suggestion than a bug.
Have this code:
use std::ffi::CString;
fn main() {
let pointer = CString::new("Hello world!").unwrap().as_ptr();
unsafe {
println!("{:?}", *pointer as u8 as char);
}
}
Rust reports the warning rustc(temporary_cstring_as_ptr) during build. The detail is this `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetime which is expected 🆗 .
If you run the code, a "random" character will be printed and that's of course unexpected. A solution is an assignment of the string into a standalone variable as explained here.
Have the same code, but this time it uses String instead of CString:
fn main() {
let pointer = String::from("Hello world!").as_ptr();
unsafe {
println!("{:?}", *pointer as char);
}
}
I expected to see this happen:
- I should get similar kind of warning as in case of
CString, because also in this case the pointer is dangling and if you run the code, a random character will be printed. A solution is the same as for CString
Instead, this happened:
Meta
rustc --version --verbose:
rustc 1.58.0-nightly (e249ce6b2 2021-10-30)
binary: rustc
commit-hash: e249ce6b2345587d6e11052779c86adbad626dff
commit-date: 2021-10-30
host: x86_64-unknown-linux-gnu
release: 1.58.0-nightly
LLVM version: 13.0.0
Playground
It's rather a suggestion than a bug.
Have this code:
Rust reports the warning
rustc(temporary_cstring_as_ptr)during build. The detail isthis `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetimewhich is expected 🆗 .If you run the code, a "random" character will be printed and that's of course unexpected. A solution is an assignment of the string into a standalone variable as explained here.
Have the same code, but this time it uses
Stringinstead ofCString:I expected to see this happen:
CString, because also in this case the pointer is dangling and if you run the code, a random character will be printed. A solution is the same as forCStringInstead, this happened:
Meta
rustc --version --verbose: