Was reading this in The Rustonomicon and couldn't help laughing:
Safe Rust is the true Rust programming language. If all you do is write Safe Rust, you will never have to worry about type-safety or memory-safety. You will never endure a null or dangling pointer, or any of that Undefined Behavior nonsense.
That's totally awesome.
And yet this is "safe" Rust that is totally wrong and will produce a memory corrupted string:
let a:LPCSTR = CString::new("Some string for Windows API").unwrap().as_ptr();
This took me two days to debug, no warning, no error.
The returned pointer will be valid for as long as self is and points
to a contiguous region of memory terminated with a 0 byte to represent
the end of the string.
If you do
let t = CString::new("Some string for Windows API").unwrap();
let a = t.as_ptr();
This will work as self is now alive, while otherwise it won't be.
Yes, I read the docs later and realized what the problem was, I guess I was assuming that temporary object would be kept alive for as long as I needed it. And it's true that actual corruption happened in unsafe block...So safe as long as I don't dereference it, got it.