Skip to content

Commit 11027eb

Browse files
committed
Tailor CString documentation for CStr
1 parent 69b352e commit 11027eb

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

library/std/src/ffi/c_str.rs

+16-10
Original file line numberDiff line numberDiff line change
@@ -1249,7 +1249,7 @@ impl CStr {
12491249
unsafe { &*(bytes as *const [u8] as *const CStr) }
12501250
}
12511251

1252-
/// Returns the inner pointer to this C string.
1252+
/// Returns a raw pointer to the start of the string.
12531253
///
12541254
/// The returned pointer will be valid for as long as `self` is, and points
12551255
/// to a contiguous region of memory terminated with a 0 byte to represent
@@ -1268,32 +1268,38 @@ impl CStr {
12681268
/// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
12691269
/// use std::ffi::CString;
12701270
///
1271-
/// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1271+
/// let ptr = {
1272+
/// let cstring = CString::new("Hello").expect("CString::new failed");
1273+
/// let cstr = cstring.as_c_str();
1274+
/// cstr.as_ptr()
1275+
/// }; // `cstring` dropped here
1276+
///
12721277
/// unsafe {
12731278
/// // `ptr` is dangling
12741279
/// *ptr;
12751280
/// }
12761281
/// ```
12771282
///
12781283
/// This happens because the pointer returned by `as_ptr` does not carry any
1279-
/// lifetime information and the [`CString`] is deallocated immediately after
1280-
/// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
1281-
/// expression is evaluated.
1282-
/// To fix the problem, bind the `CString` to a local variable:
1284+
/// lifetime information and the underlying bytes are deallocated when `bytes`
1285+
/// goes out of scope.
1286+
/// To fix the problem, keep the bytes in scope:
12831287
///
12841288
/// ```no_run
12851289
/// # #![allow(unused_must_use)]
1286-
/// use std::ffi::CString;
1290+
/// use std::ffi::CStr;
12871291
///
1288-
/// let hello = CString::new("Hello").expect("CString::new failed");
1292+
/// let bytes = *b"Hello\0";
1293+
/// let hello = CStr::from_bytes_with_nul(&bytes)
1294+
/// .expect("CStr::from_bytes_with_nul failed");
12891295
/// let ptr = hello.as_ptr();
12901296
/// unsafe {
1291-
/// // `ptr` is valid because `hello` is in scope
1297+
/// // `ptr` is valid because `bytes` is in scope
12921298
/// *ptr;
12931299
/// }
12941300
/// ```
12951301
///
1296-
/// This way, the lifetime of the [`CString`] in `hello` encompasses
1302+
/// This way, the lifetime of the [`CStr`] in `hello` encompasses
12971303
/// the lifetime of `ptr` and the `unsafe` block.
12981304
#[inline]
12991305
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)