skip to content

In Rust, why is `let p = CString::new(name).unwrap().as_ptr();` followed by a C call a bug, and when does `CString::new` fail?

level: middleimportance: should knowfreq 50%

answer

  1. a temporary and its statement
  2. the pointer carries no lifetime
  3. bind the owner to a local
  4. an interior zero byte

basics

~20 s

The CString is a temporary dropped at the end of the let statement, so p dangles before C reads it. Bind the CString to a variable that outlives the call. CString::new returns Err(NulError) when the bytes contain an interior NUL.

solid answer

~40 s

`as_ptr` returns a raw `*const c_char` that carries no lifetime, so the borrow checker cannot see that it points into the `CString`. In `let p = CString::new(name).unwrap().as_ptr();` the `CString` is a temporary, freed at the end of that statement, so `p` dangles and handing it to C is undefined behaviour. rustc 1.99 warns through `dangling_pointers_from_temporaries`, and Miri reports the freed allocation. The fix is `let c_name = CString::new(name)?; ... c_name.as_ptr()`, keeping `c_name` alive across the call; a temporary used inside one call expression is fine, because it lives until the end of that statement. `CString::new` fails with `NulError` if the input contains a zero byte, since C would stop reading there; `nul_position()` says where. For strings coming *from* C, `CStr::from_ptr` borrows them without copying.

code

rust · 6 lines
rust
use std::ffi::{CStr, CString};
fn main() {
    let p = CString::new("archive.kz").unwrap().as_ptr();
    let s = unsafe { CStr::from_ptr(p) };
    println!("{s:?}");
}

go deeper

for a junior

Recall that C strings end at a zero byte, CString adds that terminator, and CString::new fails on an interior zero byte.

for a middle

Explain temporaries dropped at the end of the statement and why a raw pointer from as_ptr escapes the borrow checker. Give the bound-variable fix and say when the inline form is fine.

for a senior

Use the lint and Miri to show it, and design wrappers that take &CStr so the compiler tracks storage. Decide between borrowing for the call and transferring ownership when C keeps the pointer.

for a principal

Push string conversions into one wrapper layer that maps NulError and Utf8Error into typed errors. Raw pointer lifetimes should never leak into application code.

## What CString and CStr are C represents text as a pointer to bytes ending in a **NUL terminator** (a zero byte). Rust's `String` and `&str` store a length instead and may contain zero bytes, so neither can be handed to C directly. The standard library has two FFI string types: | Type | Owns memory? | Typical direction | Get a pointer with | |---|---|---|---| | `std::ffi::CString` | yes, heap | Rust to C | `as_ptr()` (borrowed) or `into_raw()` (ownership moves out) | | `std::ffi::CStr` (re-exported from `core::ffi`) | no, borrowed | C to Rust, or literals | `as_ptr()` | `CString::new(bytes)` copies the input, appends a single trailing NUL, and returns `Result<CString, NulError>`. A C string literal such as `c"archive.kz"` is a `&'static CStr` checked at compile time. ## The dangling-pointer trap ```rust let p = CString::new("archive.kz").unwrap().as_ptr(); unsafe { strlen(p) } // p already dangles ``` Three facts combine here: 1. `CString::new(...).unwrap()` produces a **temporary**: a value with no variable name. 2. A temporary is dropped at the end of the **statement** that created it, here the `let`. Dropping a `CString` frees its buffer. 3. `as_ptr` returns `*const c_char`, a raw pointer with **no lifetime**. The borrow checker therefore has nothing to object to, unlike `&str`, where the same shape would fail to compile. So `p` points into freed memory before C ever sees it. The standard library's own documentation of `CStr::as_ptr` uses almost this exact line as its example of undefined behaviour. rustc 1.99 recognises the pattern and warns: ```plaintext warning: this creates a dangling pointer because temporary `CString` is dropped at end of statement = note: `#[warn(dangling_pointers_from_temporaries)]` on by default ``` Running the program under Miri gives the verdict a normal run hides: `Undefined Behavior: memory access failed: alloc310 has been freed, so this pointer is dangling`. A plain run often "works", because the freed bytes have not been reused yet. ## Fixes, and the case that is fine - **Bind the owner.** `let c_name = CString::new(name)?;` then `c_name.as_ptr()` at the call. The pointer is valid while `c_name` is alive and unmodified. - **Use it within one statement.** `unsafe { strlen(CString::new(name)?.as_ptr()) }` is sound: the temporary lives until the end of that statement, which includes the call. This is the one place the temporary form is correct, and it stops being correct if C keeps the pointer after returning. - **Prefer `&CStr` in wrapper signatures.** A safe wrapper `fn open(path: &CStr)` makes the caller own the storage and the borrow checker track it. - If C must keep the string after the call returns, borrowing is wrong. Transfer ownership with `into_raw` and reclaim it later, which belongs to the material on ownership across the boundary. Also remember that `as_ptr` returns a read-only pointer. The `CStr::as_ptr` documentation warns that writing through it, including passing it to C code that writes, is undefined behaviour. ## When CString::new fails C treats the first zero byte as the end of the string. If Rust passed `"level\0six"`, C would see only `"level"`, a silent truncation: a name that passed a check on the Rust side would mean something shorter to C. So `CString::new` refuses: ```rust let err = CString::new("level\0six").unwrap_err(); assert_eq!(err.nul_position(), 5); ``` `NulError` carries the position and gives the bytes back through `into_vec()`. Data from users or the network can contain zero bytes, so map the error to your own error type instead of calling `unwrap`. Calling `unwrap` on untrusted input turns a bad string into a panic. ## Reading strings that come from C For a `*const c_char` returned by C, wrap it with `unsafe { CStr::from_ptr(p) }`. Its documented safety requirements are: - `p` is non-null and points to a NUL terminator inside a single allocation; - the memory stays valid and unmutated for the lifetime of the returned `&CStr`, which the compiler infers from use, so tie it to something real. Then `to_str()` checks UTF-8 and returns `Result<&str, Utf8Error>`, while `to_string_lossy()` replaces invalid sequences. `CStr::from_ptr` borrows and never frees. If C allocated the string and expects you to release it, call the library's own free function after copying.

  • Why does the same shape with `&str` fail to compile while the `CString` version compiles?
    A `&str` borrowed from a temporary carries a lifetime, so the borrow checker reports that the temporary is freed while still borrowed (E0716). `CString::as_ptr` returns a raw pointer with no lifetime, so the compiler has nothing to check; only the `dangling_pointers_from_temporaries` lint warns.
  • A C function stores the `const char *` you pass and reads it later; is `as_ptr` on a local `CString` enough?
    Only if the `CString` outlives every later read, for example stored in the same struct as the C handle and dropped after it. Otherwise hand ownership over with `into_raw` and reclaim it with `from_raw` when C is done. Read the C documentation: "borrowed for the call" and "kept" need different code.

  • Using the pointer right after the let makes it safe enough.
  • The borrow checker would reject a dangling as_ptr pointer.
  • CString::new silently truncates at an interior NUL.
  • CStr::from_ptr frees the C string when the CStr is dropped.
  • It ran fine in testing, so the pointer must be valid.