Skip to content

Commit 298f8ee

Browse files
committed
Explain one more unsafe
1 parent 76d733e commit 298f8ee

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,11 @@ impl CString {
599599
/// ```
600600
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
601601
pub fn into_boxed_c_str(self) -> Box<CStr> {
602-
unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
602+
let ptr: *mut [u8] = Box::into_raw(self.into_inner());
603+
// SAFETY: Casting away the length information is fine as `CStr`'s length computation works
604+
// by counting the elements up to the first null. Since this `CString` must be null
605+
// terminated, the `CStr` can properly compute its length
606+
unsafe { Box::from_raw(ptr as *mut CStr) }
603607
}
604608

605609
/// Bypass "move out of struct which implements [`Drop`] trait" restriction.

0 commit comments

Comments
 (0)