diff options
| author | Aleksey Kladov <aleksey.kladov@gmail.com> | 2016-06-19 11:55:34 +0300 |
|---|---|---|
| committer | Aleksey Kladov <aleksey.kladov@gmail.com> | 2016-06-19 15:14:51 +0300 |
| commit | 677aa47d68b7db8bb51c651dcb73a3225b8c7d64 (patch) | |
| tree | 44ada90dc86b87a3e6c2e5ceb14b822a7f76025f /src/libstd | |
| parent | b1ae194fa665265cbabdfdd1d1d43fc8bb47362a (diff) | |
| download | rust-677aa47d68b7db8bb51c651dcb73a3225b8c7d64.tar.gz rust-677aa47d68b7db8bb51c651dcb73a3225b8c7d64.zip | |
Document `CStr::as_ptr` dangers.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/ffi/c_str.rs | 32 |
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() |
