CString Guards FFI Strings

Hand strings to C code through CString: interior NUL bytes are rejected with the offending bytes, and valid values carry exactly one terminating NUL.

RustSecurity Boundaries

Code

snippet
use std::ffi::CString;

fn main() {
    // 正常路径:无内部空字节时转换成功
    let path = CString::new("/etc/hosts").expect("no interior nul");
    println!("bytes: {:?}", path.as_bytes_with_nul());
    println!("ends with nul: {}", path.as_bytes_with_nul().last() == Some(&0));

    // 内嵌空字节是 FFI 的注入风险:CString::new 拒绝并指出问题字节
    let bad = CString::new(b"pass\x00word".to_vec());
    match bad {
        Ok(_) => println!("unexpected ok"),
        Err(err) => println!("rejected with {} nul byte(s)", err.nul_bytes().len()),
    }

    // CString 保证以单个 NUL 结尾:as_bytes_with_nul 恒含终止符
    let flag = CString::new("--verbose").unwrap();
    let raw = flag.as_bytes_with_nul();
    println!("flag bytes: {raw:?}");
    println!("last byte is nul: {}", raw[raw.len() - 1] == 0);
}

How it works

The code’s whole job belongs to the function main.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Caveats

  • Nothing beyond the runtime is required: no packages, no installation.

Using it

The entry-point signature is fn main()

The run prints bytes:, ends with nul:, unexpected ok — each prefix names the step that produced it.

Key statements

let flag = CString::new("--verbose").unwrap();

Interactive Tools for This Topic

FAQ

What does CString Guards FFI Strings print when run?
Running the file directly is enough — expect labeled output lines such as `bytes:`, `ends with nul:`, `unexpected ok`.