Why doesn't this Rust program crash?

2019-06-22 11:57发布

问题:

Consider this Rust program:

fn main() {
    let mut z : Vec<Vec<(bool,f64)>> = Vec::with_capacity(10);
    unsafe { z.set_len(10); }
    z[0] = vec!((true,1.));
    println!("{:?}", z[0]);
}

https://play.rust-lang.org/?gist=ccf387ed66a0d8b832ed&version=stable

Rust should attempt to drop z[0] when we set it, and since z[0] is uninitialized it should crash the program. However, it runs fine. Why?

回答1:

While the memory in the Vec’s heap allocation is uninitialised, it will most commonly be filled with zeros, and a zeroed Vec is an empty Vec (String and Vec have cheap constructors because they don’t make an allocation for an empty array). There is thus no allocation to free, and so it doesn’t crash in this particular case. Very slight modifications, or running it on a machine with slightly different uninitialised memory semantics, could easily cause it to crash (which would be a good thing—crashes are typically easier to debug than subtle errors).

This diagnosis can be seen to be the case.