Finally I tried example code. It caused segmentation fault. But because explanation given by @alice was clear, I immediately realized the cause. as_mut_ptr()
of slice returns *mut T
, this should not give to Box::from_raw()
in this case. Because if do such, unintentionally create Box<T>
. What we want creat is Box<[T]>
. Here is correct code.
extern "C" fn free_buf(buf: Buffer) {
let s = unsafe { std::slice::from_raw_parts_mut(buf.data, buf.len) };
- let s = s.as_mut_ptr();
- unsafe { Box::from_raw(s); }
+ unsafe { Box::from_raw(s as *mut [u8]); }
}