No, this is likely to crash. `.to_c_str()` constructs a CString, which you are 
then promptly throwing away. So your subsequent access to `c_path` is actually 
accessing freed memory.

Try something like this:

pub fn read_file(&self, path: Option<&str>) {
    let path = path.map(|s| s.to_c_str());
    let c_path = path.map_or(ptr::null(), |p| p.with_ref(|x| x));
    unsafe {
        native_read_file(self.ch, c_path) as int
    }
}

This variant will keep the CString alive inside the `path` variable, which will 
mean that your `c_path` pointer is still valid until you return from the 
function.

-Kevin

On Feb 17, 2014, at 1:06 PM, Noah Watkins <[email protected]> wrote:

> When calling a native function that takes a char* string or NULL for
> the default behavior I treat the option like this
> 
> pub fn read_file(&self, path: Option<&str>) {
>  let c_path = match path {
>    Some(ref path) => path.to_c_str().with_ref(|x| x),
>    None => ptr::null()
>  };
>  unsafe {
>    native_read_file(self.ch, c_path) as int
>   };
> }
> 
> Is this the best way to handle the situation?
> `path.to_cstr().with_ref(|x| x)` seems a bit verbose. On the other
> hand, `unwrap` says it forgets the ownership which I'm assuming means
> that the buffer won't be freed.

Attachment: smime.p7s
Description: S/MIME cryptographic signature

_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to