Skip to content

Commit a891c72

Browse files
committed
Auto merge of #31171 - dirk:dirk/safety-section-in-cstring-docs, r=steveklabnik
Also a minor language tweak to the documentation of the `ffi::CString::from_raw` function.
2 parents 035f4cc + 9cfa191 commit a891c72

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/libstd/ffi/c_str.rs

+16-4
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,18 @@ use vec::Vec;
6060
/// }
6161
/// # }
6262
/// ```
63+
///
64+
/// # Safety
65+
///
66+
/// `CString` is intended for working with traditional C-style strings
67+
/// (a sequence of non-null bytes terminated by a single null byte); the
68+
/// primary use case for these kinds of strings is interoperating with C-like
69+
/// code. Often you will need to transfer ownership to/from that external
70+
/// code. It is strongly recommended that you thoroughly read through the
71+
/// documentation of `CString` before use, as improper ownership management
72+
/// of `CString` instances can lead to invalid memory accesses, memory leaks,
73+
/// and other memory errors.
74+
6375
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
6476
#[stable(feature = "rust1", since = "1.0.0")]
6577
pub struct CString {
@@ -207,11 +219,11 @@ impl CString {
207219
CString { inner: v.into_boxed_slice() }
208220
}
209221

210-
/// Retakes ownership of a CString that was transferred to C.
222+
/// Retakes ownership of a `CString` that was transferred to C.
211223
///
212-
/// The only appropriate argument is a pointer obtained by calling
213-
/// `into_raw`. The length of the string will be recalculated
214-
/// using the pointer.
224+
/// This should only ever be called with a pointer that was earlier
225+
/// obtained by calling `into_raw` on a `CString`. Additionally, the length
226+
/// of the string will be recalculated from the pointer.
215227
#[stable(feature = "cstr_memory", since = "1.4.0")]
216228
pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
217229
let len = libc::strlen(ptr) + 1; // Including the NUL byte

0 commit comments

Comments
 (0)