5

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?

yong
  • 3,583
  • 16
  • 32
  • 3
    I'd guess it's due to an implementation detail concerning `z..set_len`. Once you use unsafe semantics (in any language), all bets are off. It would probably crash later, when you tried to access whatever is stored at the location that assignment to `z[0]` overwrote, if any. – jpaugh Jul 09 '15 at 03:23

1 Answers1

7

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.

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215