Closed as duplicate of#78691
Closed as duplicate of#78691
Description
Consider this basic dangling pointer from a temporary:
use std::ffi::CString;
unsafe extern "C" {
fn g(v: *const i8);
}
pub fn f1(s: &str) {
let p = CString::new(s).unwrap().as_ptr();
unsafe { g(p); }
}
It produces a warning. Very good.
However, if instead we have an Option<&str>
and we use some Option
methods to convert it to a pointer, we no longer get a warning:
use std::ptr;
use std::ffi::CString;
unsafe extern "C" {
fn g(v: *const i8);
}
pub fn f2(s: Option<&str>) {
let p = s.map(|v| CString::new(v).unwrap()).map_or(ptr::null(), |v| v.as_ptr());
unsafe { g(p); }
}
I believe the closure passed to map_or
should be triggering the warning: it takes Option<CString>
as an argument, it calls as_ptr()
, it drops the Option<CString>
, and then it makes use of the pointer (to return it).