Sub topic 4
Passing strings with CString and CStr
This chapter covers how Rust text becomes a C string and how a C string becomes Rust text. It assumes you can declare and call an extern "C" function inside an unsafe block. It also assumes you know the difference between String, &str and raw pointers, and that you have a recent stable toolchain (Rust 1.82 or later for unsafe extern blocks).
Why Rust strings do not fit C
A C string is a pointer to bytes that ends at the first zero byte. The length is not stored anywhere. Code finds it by scanning for the terminator, which is how strlen works.
A Rust &str is the opposite. It is a pointer plus a length, and it is always valid UTF-8. It is not nul-terminated, and it may contain zero bytes in the middle.
Passing s.as_ptr() from a &str straight to C is therefore a bug. C would read past the end of the text until it happened to find a zero byte. The standard library gives you two types to bridge the gap:
| Type | Direction | Owns its bytes | Rust analogue |
|---|---|---|---|
| `CString` | Rust to C | Yes | `String` |
| `CStr` | C to Rust (or borrowed) | No | `&str` |
Both guarantee one thing: the bytes end with exactly one nul, and there is no nul before it. Neither guarantees UTF-8.
Building a CString
CString::new accepts anything that converts into Vec<u8>. It appends the terminator and checks that no zero byte appears earlier. If one does, it returns a NulError.
use std::ffi::CString;
fn main() {
let ok = CString::new("hello").unwrap();
println!("{:?}", ok.as_bytes_with_nul());
match CString::new("he\0llo") {
Ok(_) => unreachable!(),
Err(e) => println!("interior nul at byte {}", e.nul_position()),
}
}This prints [104, 101, 108, 108, 111, 0] and then interior nul at byte 2. The error is real input handling, not a theoretical case. A user-supplied file name or a network string can contain a zero byte. Return the error to your caller instead of calling unwrap on untrusted data.
Literals
Since Rust 1.77 you can write a C string literal with a c prefix. The compiler checks it and adds the terminator, so the type is &'static CStr and nothing is allocated.
use std::ffi::c_char;
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
}
fn main() {
let n = unsafe { strlen(c"hello".as_ptr()) };
println!("{n}");
}This prints 5. Use c"..." whenever the text is known at compile time.
The dangling pointer trap
as_ptr borrows from the CString. It does not extend the CString's life. If the owner is dropped, the pointer dangles.
use std::ffi::{c_char, CString};
fn main() {
// Wrong: the temporary CString is dropped at the end of this statement.
let p: *const c_char = CString::new("hi").unwrap().as_ptr();
// Right: bind the owner to a name that outlives every use of the pointer.
let owner = CString::new("hi").unwrap();
let q: *const c_char = owner.as_ptr();
let _ = (p, q); // p must never be dereferenced
}The first line compiles, and recent compilers warn about it. Reading through p would be undefined behavior. A common variant is unsafe { f(CString::new(s).unwrap().as_ptr()) }. That one is fine, because the temporary lives until the end of the whole statement, including the call. The trouble starts only when you store the pointer and use it later.
The c_char type
C's char is signed on some platforms and unsigned on others. Rust's std::ffi::c_char follows the target, so use it in declarations instead of i8 or u8. Your code then builds on both kinds of platform.
Reading a C string with CStr
CStr::from_ptr is unsafe. It scans for the terminator and returns a &CStr that borrows the C memory. You must guarantee all of these:
- The pointer is non-null.
- It points to bytes that end in a nul.
- The memory stays valid and unmodified for as long as the reference lives.
This example calls getenv, which returns a pointer into the process environment, or null if the variable is unset.
use std::ffi::{c_char, CStr, CString};
unsafe extern "C" {
fn getenv(name: *const c_char) -> *const c_char;
}
fn env_var(name: &str) -> Option<String> {
let name = CString::new(name).ok()?;
let ptr = unsafe { getenv(name.as_ptr()) };
if ptr.is_null() {
return None;
}
let value = unsafe { CStr::from_ptr(ptr) };
Some(value.to_string_lossy().into_owned())
}
fn main() {
println!("{:?}", env_var("HOME"));
println!("{:?}", env_var("NO_SUCH_VARIABLE_12345"));
}Two details matter here. First, the null check comes before from_ptr, because C functions use null to mean "nothing". Second, the result is copied into an owned String. The &CStr points into memory that C controls. Another thread calling setenv could invalidate it, so copy before you return.
Choosing a conversion
A CStr holds bytes, and the bytes may not be valid UTF-8. You pick how to handle that:
to_str()returnsResult<&str, Utf8Error>. Use it when invalid text should be an error.to_string_lossy()returns aCow<str>and replaces invalid sequences withU+FFFD. Use it for logs and messages.to_bytes()returns the bytes without the terminator. Use it when the data is not text, such as a Latin-1 name or a binary key.to_owned()returns aCString, which is a copy you can keep.
Fixed-size buffers
Some C APIs fill a buffer you supply, such as char buf[64]. The text ends at the first zero, and the rest of the array is leftover. CStr::from_bytes_until_nul finds that end without any unsafe.
use std::ffi::CStr;
fn main() {
let buf: [u8; 8] = *b"abc\0\0\0\0\0";
let s = CStr::from_bytes_until_nul(&buf).unwrap();
println!("{}", s.to_str().unwrap());
}This prints abc. It returns an error if the buffer has no zero byte. That case happens when C truncates a long string without terminating it, so handle the error. CStr::from_bytes_with_nul is the strict variant. It requires the nul to be the last byte, with none before it.
Who frees the string
A pointer type does not say who owns the memory. You must read the C library's documentation and follow its rule. These are the usual cases:
| C function returns | Owner | What you do |
|---|---|---|
| Pointer into static or library-internal data (`getenv`, `strerror`) | The library | Borrow with `CStr`, copy if you need it later. Never free it. |
| Heap string the caller must release (`strdup`-style) | You | Copy out, then call the library's matching free function. |
| Pointer into a handle's internal buffer | The handle | Valid only until the handle changes or is freed. Copy it. |
Free with the function the library names. A string allocated with C's malloc must be released with free, or with the library's own release function if it has one. Rust's allocator is separate, and mixing them is undefined behavior.
This wrapper handles a hypothetical API where the caller frees the result.
use std::ffi::{c_char, CStr};
// Assumed C API:
// char *make_greeting(const char *name); /* heap string, NULL on failure */
// void free_string(char *s); /* releases a make_greeting result */
unsafe extern "C" {
fn make_greeting(name: *const c_char) -> *mut c_char;
fn free_string(s: *mut c_char);
}
pub fn greeting(name: &CStr) -> Option<String> {
let raw = unsafe { make_greeting(name.as_ptr()) };
if raw.is_null() {
return None;
}
let text = unsafe { CStr::from_ptr(raw) }.to_string_lossy().into_owned();
unsafe { free_string(raw) };
Some(text)
}The function takes &CStr, so callers can pass a c"..." literal without allocating. Because it copies before freeing, the returned String has no ties to C memory.
Giving a string to C permanently
Sometimes C keeps a Rust-allocated string past the call, or Rust returns a string to a C caller. CString::into_raw gives up Rust's ownership and returns a *mut c_char. The matching CString::from_raw takes it back so Rust can free it. You must provide both halves.
use std::ffi::{c_char, CString};
#[unsafe(no_mangle)]
pub extern "C" fn rust_version_string() -> *mut c_char {
CString::new("1.0.0").unwrap().into_raw()
}
/// # Safety
/// `s` must be null or a pointer returned by `rust_version_string`, not yet freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_string_free(s: *mut c_char) {
if !s.is_null() {
drop(unsafe { CString::from_raw(s) });
}
}Paths and operating system strings
File names are not always valid UTF-8, so converting a Path through &str can lose data. On Unix you can pass the raw bytes instead.
use std::ffi::{CString, NulError};
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
fn path_to_c(p: &Path) -> Result<CString, NulError> {
CString::new(p.as_os_str().as_bytes())
}This compiles only on Unix. On Windows, native paths are 16-bit wide strings, so most C APIs there use a different pointer type, and you need a different conversion.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Passing `str::as_ptr()` to C | C reads past the text | Build a `CString` or use `c"..."` |
| Storing `as_ptr()` of a temporary | Dangling pointer | Keep the owner in a variable |
| Calling `CStr::from_ptr` on null | Undefined behavior | Check `is_null()` first |
| Calling `unwrap` on `CString::new` for user input | Panic on interior nul | Return the `NulError` |
| Freeing a library-owned string | Double free or crash | Read the ownership rule in the docs |
| Using `i8` for `char` | Fails to build on some targets | Use `c_char` |
| Assuming C text is UTF-8 | Wrong or failed conversion | Choose `to_str` or `to_string_lossy` deliberately |
Exercise
A colleague writes let p = CString::new(name).unwrap().as_ptr(); unsafe { takes_str(p) }; and it passes tests. Explain the bug and show the fix.
Show answer
The CString is a temporary that is dropped at the end of the first statement, so p dangles when takes_str runs. The tests pass only because the freed memory often still holds the old bytes. Fix it by binding the owner: let owned = CString::new(name).unwrap(); unsafe { takes_str(owned.as_ptr()) };. The owner now lives past the call. Also replace unwrap with error handling if name can come from outside the program.
Exercise
A C function const char *lib_last_error(void) returns a pointer to a buffer inside the library that is overwritten by the next call. Write a safe Rust function last_error() -> Option<String> and say why it copies the text.
Show answer
Declare fn lib_last_error() -> *const c_char; in an unsafe extern "C" block. Then check the pointer and copy:
let ptr = unsafe { liblasterror() };
if ptr.isnull() { return None; }
Some(unsafe { CStr::fromptr(ptr) }.tostringlossy().into_owned())
It copies because the library owns the buffer and reuses it on the next call, so a borrowed &CStr could change or become invalid. It does not free the pointer, because the library owns it.