Lifetime of an inner temporary



I need to get an FFI CString pointer from an Option<&str>.

I am considering a code like this:

// display: Option<&str>
let mut screen_num : c_int = 0;
let cconn = xcb_connect(
        |s| { CString::new(s).unwrap().as_ptr() }
    &mut screen_num

Lifetime of the CString (and its inner data) looks wrong to me but it allows to keep code clean and readable.
This executes without failure, but I am wondering if it is by any luck of data persistence.

any idea on this?


Your suspicion is correct: CString is destroyed before the closure returns what by then is a dangling pointer. CString needs to live longer than the xcb_connect call, e.g.

let display =|s| CString::new(s).unwrap());
let cconn = xcb_connect(
    display.map_or(null(), |s| s.as_ptr()),
    &mut screen_num,



I tried to do code such as yours but I missed the Option<CString> thing.
Exactly what I needed.

thanks a lot!