@@ -1249,7 +1249,7 @@ impl CStr {
1249
1249
unsafe { & * ( bytes as * const [ u8 ] as * const CStr ) }
1250
1250
}
1251
1251
1252
- /// Returns the inner pointer to this C string.
1252
+ /// Returns a raw pointer to the start of the string.
1253
1253
///
1254
1254
/// The returned pointer will be valid for as long as `self` is, and points
1255
1255
/// to a contiguous region of memory terminated with a 0 byte to represent
@@ -1268,32 +1268,38 @@ impl CStr {
1268
1268
/// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
1269
1269
/// use std::ffi::CString;
1270
1270
///
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
+ ///
1272
1277
/// unsafe {
1273
1278
/// // `ptr` is dangling
1274
1279
/// *ptr;
1275
1280
/// }
1276
1281
/// ```
1277
1282
///
1278
1283
/// 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:
1283
1287
///
1284
1288
/// ```no_run
1285
1289
/// # #![allow(unused_must_use)]
1286
- /// use std::ffi::CString ;
1290
+ /// use std::ffi::CStr ;
1287
1291
///
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");
1289
1295
/// let ptr = hello.as_ptr();
1290
1296
/// unsafe {
1291
- /// // `ptr` is valid because `hello ` is in scope
1297
+ /// // `ptr` is valid because `bytes ` is in scope
1292
1298
/// *ptr;
1293
1299
/// }
1294
1300
/// ```
1295
1301
///
1296
- /// This way, the lifetime of the [`CString `] in `hello` encompasses
1302
+ /// This way, the lifetime of the [`CStr `] in `hello` encompasses
1297
1303
/// the lifetime of `ptr` and the `unsafe` block.
1298
1304
#[ inline]
1299
1305
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
0 commit comments