Lifetime of an inner temporary


#1

Hi

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(
    display.map_or(
        null(),
        |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?
Thanks,
RĂ©mi


#2

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 = display.map(|s| CString::new(s).unwrap());
let cconn = xcb_connect(
    display.map_or(null(), |s| s.as_ptr()),
    &mut screen_num,
);

#3

Haha!

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

thanks a lot!