Some C code calls into the Rust open
call below which returns a pointer. Later the C code passes the exact same pointer back to the close
function which tries to drop (free) it. It segfaults in free(3)
. Why?
use std::os::raw::{c_int, c_void};
struct Handle;
extern "C" fn open(_readonly: c_int) -> *mut c_void {
let h = Handle;
let h = Box::new(h);
return Box::into_raw(h) as *mut c_void;
}
extern "C" fn close(h: *mut c_void) {
let h = unsafe { Box::from_raw(h) };
// XXX This segfaults - why?
drop(h);
}
rustfmt
to ensure that your code matches the style guidelines – hellowextern "C"
. It segfaults nevertheless play.rust-lang.org/… – hellowleak
returns the inner T, but that can't be cast to the finalvoid*
– RichBox::into_raw
"forgets" theBox
, so theBox
is not dropped whenopen
returns. – Francis Gagné