From 00a7b56bab317d9f1aaa5255145ce3414081cbfe Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Wed, 3 Jun 2020 23:32:26 +0200 Subject: [PATCH 1/2] Added the documentation about length to CString::from_raw --- src/libstd/ffi/c_str.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 4bac9a4917d8f..3d7ac724fbd5a 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -395,6 +395,12 @@ impl CString { /// ownership of a string that was allocated by foreign code) is likely to lead /// to undefined behavior or allocator corruption. /// + /// It should be noted that the length isn't just "recomputed," but that + /// the recomputed length must match the original length from the + /// [`into_raw`] call. This means the [`into_raw`]/`from_raw` methods + /// should not be used when passing the string to C functions that can + /// modify the string's length. + /// /// > **Note:** If you need to borrow a string that was allocated by /// > foreign code, use [`CStr`]. If you need to take ownership of /// > a string that was allocated by foreign code, you will need to From 87abe174c46bf10246369e63a36eccd6748b7dbe Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Wed, 3 Jun 2020 23:55:41 +0200 Subject: [PATCH 2/2] Added a warning to CString::into_raw too --- src/libstd/ffi/c_str.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 3d7ac724fbd5a..b324b1618966b 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -446,6 +446,11 @@ impl CString { /// /// Failure to call [`from_raw`] will lead to a memory leak. /// + /// The C side must **not** modify the length of the string (by writing a + /// `NULL` somewhere inside the string or removing the final one) before + /// it makes it back into Rust using [`from_raw`]. See the safety section + /// in [`from_raw`]. + /// /// [`from_raw`]: #method.from_raw /// /// # Examples