Why doesn't this Rust program crash?

倾然丶 夕夏残阳落幕 提交于 2019-12-10 14:54:59

问题


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.



来源:https://stackoverflow.com/questions/31307454/why-doesnt-this-rust-program-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!