std-method

Borrow a raw C string pointer without transferring ownership

A pointer alone cannot prove that a foreign string is readable or terminated. The caller must guarantee a non-null pointer, a readable initialized sequence through its terminator within one allocation, a representable length and no mutation during the borrow. Here the owner is local and remains alive. Expected stdout (not executed): rust Common mistake: Saving the pointer from a temporary CString after the temporary is dropped.

Formal Syntax & Structure

rust syntaxrust
unsafe { CStr::from_ptr(ptr) }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::ffi::{CStr, CString};    let owner = CString::new("rust").unwrap();    let ptr = owner.as_ptr();    // SAFETY: owner is alive and immutable throughout the borrow; it supplies a valid terminated string.    let borrowed = unsafe { CStr::from_ptr(ptr) };    println!("{}", borrowed.to_str().unwrap());}
Rust Reference