std-method
Borrow a C string from terminated bytes
Use this safe constructor when a borrowed byte slice contains exactly one final zero. It rejects missing terminators and interior zeros; it does not allocate or validate UTF-8. Expected stdout (not executed): cat true Common mistake: Using from_ptr when the input is already a bounded byte slice.
Formal Syntax & Structure
rust syntaxrust
CStr::from_bytes_with_nul(bytes)Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::ffi::CStr; let text = CStr::from_bytes_with_nul(b"cat\0").unwrap(); println!("{} {}", text.to_str().unwrap(), CStr::from_bytes_with_nul(b"cat").is_err());}