Fix a call that passes s.as_ptr() from a Rust &str to C's strlen
c_len should return the length of a Rust string as C's strlen sees it. The crate uses edition 2024, and the file does not build: error: extern blocks must be unsafe. A colleague says that adding unsafe before extern is the whole fix. Explain why it is not, and rewrite the code.
Requirements:
- Keep
c_len(s: &str) -> Option<usize>; returnNonewhenscontains a NUL byte. strlenmust only ever receive a valid, NUL-terminated buffer.- Mark every
unsafeblock with a// SAFETY:comment.
use std::ffi::c_char;
extern "C" {
fn strlen(s: *const c_char) -> usize;
}
fn c_len(s: &str) -> Option<usize> {
Some(unsafe { strlen(s.as_ptr() as *const c_char) })
}
fn main() {
println!("{:?}", c_len("hello"));
}Find and fix the bug.
A &str has no trailing NUL, so strlen reads past its end: undefined behaviour. Declare unsafe extern "C", keep a CString::new(s).ok()? in a variable and pass its as_ptr(); a literal like c"hello" is already a &CStr.
- Believing Rust strings end with a NUL byte the way C strings do
- Taking
as_ptr()from a temporaryCString, which is dropped at the end of the statement - Thinking
unsafe externalone makes the call correct, when it only states a promise
- How do you turn a
*const c_charreturned by C back into a RustStringsafely? - Why does
strlenreturn 12 for the Russian word «привет» rather than 6?
The compiler's message is only the first problem. A Rust string is UTF-8 with a length and no trailing NUL byte, while strlen walks memory until it meets a zero. For "hello" it reads five bytes and keeps going — past the end of the string. That is undefined behaviour: what such a program prints cannot be predicted, and one lucky run proves nothing. unsafe before extern is required, but it only records the promise that the signature matches the real one; it does not check the argument. The code below is built with rustc 1.99:
use std::ffi::{CStr, CString, c_char};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
}
fn c_len(s: &str) -> Option<usize> {
let owned = CString::new(s).ok()?; // copies s and appends a NUL; None for an interior NUL
// SAFETY: owned lives until the end of the function, and its buffer ends in a NUL.
Some(unsafe { strlen(owned.as_ptr()) })
}
fn c_len_of(s: &CStr) -> usize {
// SAFETY: &CStr guarantees a non-null pointer to a NUL-terminated string.
unsafe { strlen(s.as_ptr()) }
}
fn main() {
println!("{:?}", c_len("hello")); // Some(5)
println!("{:?}", c_len("he\0llo")); // None
println!("{}", c_len_of(c"hello")); // 5
}CString owns a copy of the string with a zero at the end; CString::new returns an error if a zero is already inside, because C would otherwise see a truncated string. The trap: let p = CString::new(s).ok()?.as_ptr(); — the temporary CString is dropped at the end of the statement, the pointer dangles, and the compiler warns this creates a dangling pointer because temporary `CString` is dropped at end of statement. That is why the CString goes into a variable. When the string is known at compile time, the literal c"hello" gives a &CStr directly, and a function that takes a &CStr cannot be handed a string without a zero at all.