Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

Rust CString and CStr

Reference for Rust CString and CStr: NUL-terminated strings for C interop, c"" literals, NulError, from_bytes_with_nul, to_str and calling C functions.

C functions expect strings that end with a zero byte and contain no zero byte anywhere else. Rust strings are different: they store their length, may contain \0, and have no terminator. CString is the owned, NUL-terminated string you build in Rust to hand to C, and CStr is the borrowed view (like String and str) used to read a string that C gave you.

Creating a CString checks for interior zero bytes and appends the terminator. Since Rust 1.77 you can also write a C string literal, c"hello", which is a &CStr checked at compile time. Neither type promises UTF-8: C strings are just bytes.

Rust
use std::ffi::CString;
let name = CString::new("Ada").unwrap();

Try it

Rust Creating and inspecting C strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Calling a C function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn CString::new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError>
fn CStr::as_ptr(&self) -> *const c_char
fn CString::into_string(self) -> Result<String, IntoStringError>
unsafe fn CStr::from_ptr<'a>(ptr: *const c_char) -> &'a CStr
fn CStr::from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError>
fn CStr::from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError>
fn CStr::to_str(&self) -> Result<&str, Utf8Error>
fn CStr::to_string_lossy(&self) -> Cow<'_, str>
Name Description
t Bytes or text that become the string body. A trailing zero is added for you.
ptr A pointer to a NUL-terminated string.
bytes A byte slice that contains the string; from_bytes_with_nul needs exactly one zero, at the end.

Returns: CString::new returns Err(NulError) if the input contains a zero byte; the error exposes nul_position() and into_vec(). to_str fails with Utf8Error for non-UTF-8 content.

Errors / panics / edge cases: from_ptr is unsafe: the pointer must be non-null, valid until the first zero byte, and the memory must not change while the &CStr lives. Passing a dangling or unterminated pointer is undefined behavior.

Usage notes

  • Keep the CString alive. CString::new("x").unwrap().as_ptr() creates a temporary that is dropped at the end of the statement, leaving a dangling pointer. Bind it to a variable first.
  • as_ptr() gives a borrowed pointer. Use into_raw() to give ownership to C, and take it back with CString::from_raw to free it exactly once. Never pass this pointer to C's free.
  • The terminator is not counted. count_bytes() and as_bytes() leave it out; as_bytes_with_nul() includes it.
  • c_char is i8 or u8 depending on the platform. Use std::ffi::c_char rather than a hard-coded type.
  • Edition 2024 requires unsafe extern for blocks that declare foreign functions; calling them still needs unsafe.
  • Lossy decoding with to_string_lossy is the right default for printing data you do not control.
  • For file paths use Path and OsStr, and convert with OsStrExt::as_bytes on Unix before making a CString.
  • Cost: new copies the bytes once and scans for zero bytes.