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.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.