std-method
CString::new rejects interior NUL bytes
Create an owned C string from bytes. The constructor appends a final zero and rejects zeros inside the input. Handle the error rather than silently truncating user data. Expected stdout (not executed): [99, 97, 116, 0] 1 Common mistake: Assuming CString::new removes embedded zeros.
Formal Syntax & Structure
rust syntaxrust
CString::new(bytes) -> Result<CString, NulError>Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::ffi::CString; let good = CString::new("cat").unwrap(); let bad = CString::new(b"a\0b".as_slice()).unwrap_err(); println!("{:?} {}", good.as_bytes_with_nul(), bad.nul_position());}