× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Why doesn't this Rust program crash?

Chris Morgan
Jul 15, 2015
<p>While the memory in the Vec’s heap allocation is uninitialised, it will most commonly be filled with zeros, and a zeroed <code>Vec</code> is an empty <code>Vec</code> (<code>String</code> and <code>Vec</code> 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).</p> <p><a href="https://play.rust-lang.org/?code=fn%20main()%20%7B%0A%20%20%20%20let%20mut%20z%3A%20Vec%3CVec%3C(bool%2Cf64)%3E%3E%20%3D%20Vec%3A%3Awith_capacity(10)%3B%0A%20%20%20%20unsafe%20%7B%20z.set_len(10)%3B%20%7D%0A%0A%20%20%20%20%2F%2F%20(Just%20confirming%20that%20Vec%20is%20three%20words.)%0A%20%20%20%20assert_eq!(std%3A%3Amem%3A%3Asize_of%3A%3A%3CVec%3C(bool%2C%20f64)%3E%3E()%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20std%3A%3Amem%3A%3Asize_of%3A%3A%3C%5Busize%3B%203%5D%3E())%3B%0A%0A%20%20%20%20let%20raw%3A%20%5Busize%3B%203%5D%20%3D%20unsafe%20%7B%20std%3A%3Aptr%3A%3Aread(std%3A%3Amem%3A%3Atransmute(%26z%5B0%5D))%20%7D%3B%0A%20%20%20%20println!(%22Raw%20words%20of%20z%5B0%5D%3A%20%7B%3A%3F%7D%22%2C%20raw)%3B%0A%20%20%20%20z%5B0%5D%20%3D%20vec!((true%2C1.))%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20z%5B0%5D)%3B%0A%7D&amp;version=stable" rel="nofollow">This diagnosis can be seen to be the case.</a></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31307454/Why%20doesn't%20this%20Rust%20program%20crash?/31308265">Stack Overflow</a>.</p>
comments powered by Disqus