Skip to content

Commit 71b526b

Browse files
committed
Add section about memory safety to ffi::CString documentation
Also a minor language tweak to the documentation of the `ffi::CString::from_raw` function.
1 parent 0486e12 commit 71b526b

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 15 additions & 3 deletions
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 {
@@ -209,9 +221,9 @@ impl CString {
209221

210222
/// 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)