Closed
Description
ℹThis report has previously been discussed in Why is a warning suppressed when the code is inside of a macro? - help - The Rust Programming Language Forum
I tried this code:
use std::ffi::CString;
use std::os::raw::c_char;
extern "C" {
fn puts(s: *const c_char);
}
macro_rules! mymacro {
() => {
puts(CString::new("A CString").unwrap().as_ptr());
};
}
fn main() {
unsafe {
puts(CString::new("A CString").unwrap().as_ptr());
mymacro!();
}
}
When executing, it does evaluate the code twice:
A CString
A CString
I expected to see a warning for each time I wrote CString::new("A CString").unwrap().as_ptr()
Instead, only one warning was fired.
See Warning (click me)
warning: getting the inner pointer of a temporary `CString`
--> src/main.rs:16:49
|
16 | puts(CString::new("A CString").unwrap().as_ptr());
| ---------------------------------- ^^^^^^ this pointer will be invalid
| |
| this `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetime
|
= note: `#[warn(temporary_cstring_as_ptr)]` on by default
= note: pointers do not have a lifetime; when calling `as_ptr` the `CString` will be deallocated at the end of the statement because nothing is referencing it as far as the type system is concerned
= help: for more information, see https://doc.rust-lang.org/reference/destructors.html
rustc --version --verbose
:
rustc 1.58.1 (db9d1b20b 2022-01-20)
binary: rustc
commit-hash: db9d1b20bba1968c1ec1fc49616d4742c1725b4b
commit-date: 2022-01-20
host: x86_64-pc-windows-msvc
release: 1.58.1
LLVM version: 13.0.0```