1

I am writing a safe wrapper around a c library in rust, and I found a weird behaviour:

// this works
let string = CString::new(filename).expect("error saving image");
let bytes = string.as_bytes_with_nul();
let ptr = bytes.as_ptr();
let image = unsafe { load_image_color(ptr as *mut c_char, width.into(), height.into()) };

//this panics with "STB Reason: can't fopen" as the string passed seems to be null ("")
let string = CString::new(filename)
    .expect("error loading image")
    .as_bytes_with_nul()
    .as_ptr();
let image = unsafe { load_image_color(string as *mut c_char, width.into(), height.into()) };

Can someone please explain to me why these two pieces of code are not semantically equivalent??

Le Marin
  • 135
  • 1
  • 12
  • The second piece leads to undefined behavior because the actual string (behind the value of type `CString`) is released right after you obtain a raw pointer to it. – E_net4 Dec 05 '19 at 20:55
  • 5
    [It is your responsibility to make sure that the underlying memory is not freed too early.](https://doc.rust-lang.org/std/ffi/struct.CString.html#method.as_ptr) You might have meant `into_raw`, not `as_ptr`. – trent Dec 05 '19 at 21:18

0 Answers0