about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorGuillaume Gomez <guillaume1.gomez@gmail.com>2016-06-21 23:54:28 +0200
committerGitHub <noreply@github.com>2016-06-21 23:54:28 +0200
commit3f43b0168182aa970390004aaad08f73f2915a7e (patch)
tree89a1c6c0c336a85fd441f40ea9accd223d49af54 /src/libstd
parentfe96928d7de991e527a7ed7b88bb30aa965c8a08 (diff)
parent677aa47d68b7db8bb51c651dcb73a3225b8c7d64 (diff)
downloadrust-3f43b0168182aa970390004aaad08f73f2915a7e.tar.gz
rust-3f43b0168182aa970390004aaad08f73f2915a7e.zip
Rollup merge of #34356 - matklad:cstr-docs, r=GuillaumeGomez
Document `CStr::as_ptr` dangers.

r? @steveklabnik

Hi! I've tried to document `CString::new("hello").unwrap().as_ptr()` footgun. Related [RFC] and the original [discussion].

[RFC]: https://github.com/rust-lang/rfcs/pull/1642
[discussion]: https://users.rust-lang.org/t/you-should-stop-telling-people-that-safe-rust-is-always-safe/6094
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/ffi/c_str.rs32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs
index 2bc7585f5fb..0d3e18f9b96 100644
--- a/src/libstd/ffi/c_str.rs
+++ b/src/libstd/ffi/c_str.rs
@@ -509,6 +509,38 @@ impl CStr {
     /// The returned pointer will be valid for as long as `self` is and points
     /// to a contiguous region of memory terminated with a 0 byte to represent
     /// the end of the string.
+    ///
+    /// **WARNING**
+    ///
+    /// It is your responsibility to make sure that the underlying memory is not
+    /// freed too early. For example, the following code will cause undefined
+    /// behaviour when `ptr` is used inside the `unsafe` block:
+    ///
+    /// ```no_run
+    /// use std::ffi::{CString};
+    ///
+    /// let ptr = CString::new("Hello").unwrap().as_ptr();
+    /// unsafe {
+    ///     // `ptr` is dangling
+    ///     *ptr;
+    /// }
+    /// ```
+    ///
+    /// This happens because the pointer returned by `as_ptr` does not carry any
+    /// lifetime information and the string is deallocated immediately after
+    /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
+    /// To fix the problem, bind the string to a local variable:
+    ///
+    /// ```no_run
+    /// use std::ffi::{CString};
+    ///
+    /// let hello = CString::new("Hello").unwrap();
+    /// let ptr = hello.as_ptr();
+    /// unsafe {
+    ///     // `ptr` is valid because `hello` is in scope
+    ///     *ptr;
+    /// }
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn as_ptr(&self) -> *const c_char {
         self.inner.as_ptr()