Whilst the documentation explicitly mentions the situation, precise scope is easy to get wrong.
// .as_ptr returns an internal pointer into the CString, and may be invalidated when the
// CString falls out of scope (the destructor will run, freeing the allocation if there is
// one).
let s = "foo";
let s1 = s.to_c_str(); // Ok.
let s2 = s.to_c_str().as_ptr(); // Oops.
// ^~~~ tmp CString falls out of scope.
let (c1, c2) = unsafe{ (*s1.as_ptr(), *s2) };
println!("{}, {}", c1, c2); // Prints `102, 0'
The same pattern is even easier to overlook in e.g libc::open(filename.to_c_str().as_ptr(), ...).
String's with_c_str should probably be preferred (or documented as preferred).
Whilst the documentation explicitly mentions the situation, precise scope is easy to get wrong.
The same pattern is even easier to overlook in e.g
libc::open(filename.to_c_str().as_ptr(), ...).String's
with_c_strshould probably be preferred (or documented as preferred).