C strings and ownership contracts
Quick answer
C strings use a terminating zero byte, whereas Rust str values are length-delimited UTF-8. CString owns a C-compatible string; CStr provides a borrowed view.
Keep allocation ownership explicit
CString::new rejects interior zero bytes. A C pointer borrowed from CString is usable only while the owner lives and the foreign operation obeys its access contract. into_raw transfers ownership; return that exact allocation to CString::from_raw once, without changing its terminating length. Do not free it using an unrelated C allocator. A borrowed CStr may contain non-UTF-8 data.
use std::ffi::CString;fn main() { let s = CString::new("cat").unwrap(); println!("{:?}", s.as_c_str().to_bytes_with_nul()); println!("{}", CString::new(b"a\0b".as_slice()).is_err());}Expected stdout (not executed):
[99, 97, 116, 0]trueThe trailing zero is stored explicitly and an interior zero is rejected.
use std::ffi::CString;fn main() { let p = CString::new("local").unwrap().into_raw(); // SAFETY: p came from into_raw above, was never accessed or changed, // and is reconstructed exactly once. let s = unsafe { CString::from_raw(p) }; println!("{}", s.to_str().unwrap());}Expected stdout (not executed):
localThe reconstructed CString releases its own allocation at scope exit.
Common mistake
Do not retain a borrowed C pointer after its CString owner has been dropped.
Try it yourself
Explain the difference between borrowing a pointer with as_ptr and transferring it with into_raw.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
C strings and ownership contracts — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A CString is converted with into_raw and later returned unchanged. Which operation restores Rust ownership?
C strings and ownership contracts — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::ffi::CString; fn main() { let s = CString::new("cat").unwrap(); println!("{:?}", s.as_c_str().to_bytes_with_nul()); println!("{}", CString::new(b"a\0b".as_slice()).is_err()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
C strings and ownership contracts — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::ffi::CString; fn main() { let p = CString::new("local").unwrap().into_raw(); // SAFETY: p came from into_raw above, was never accessed or changed, // and is reconstructed exactly once. let s = unsafe { CString::from_raw(p) }; println!("{}", s.to_str().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.