Skip to content

Commit 4db8c9f

Browse files
committed
Add doc example for CString::into_raw.
1 parent ae79201 commit 4db8c9f

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,26 @@ impl CString {
288288
/// Failure to call [`from_raw`] will lead to a memory leak.
289289
///
290290
/// [`from_raw`]: #method.from_raw
291+
///
292+
/// # Examples
293+
///
294+
/// ```
295+
/// use std::ffi::CString;
296+
///
297+
/// let c_string = CString::new("foo").unwrap();
298+
///
299+
/// let ptr = c_string.into_raw();
300+
///
301+
/// unsafe {
302+
/// assert_eq!(b'f', *ptr as u8);
303+
/// assert_eq!(b'o', *ptr.offset(1) as u8);
304+
/// assert_eq!(b'o', *ptr.offset(2) as u8);
305+
/// assert_eq!(b'\0', *ptr.offset(3) as u8);
306+
///
307+
/// // retake pointer to free memory
308+
/// let _ = CString::from_raw(ptr);
309+
/// }
310+
/// ```
291311
#[stable(feature = "cstr_memory", since = "1.4.0")]
292312
pub fn into_raw(self) -> *mut c_char {
293313
Box::into_raw(self.into_inner()) as *mut c_char

0 commit comments

Comments
 (0)