Rust runtime error: Illegal instruction: 4

use std::intrinsics;
#[deriving(Show)]
struct NewType<'a, T: 'a> {
    a:int,
    b:String,
    v: &'a T
}
fn main() {
        let t: NewType<int> = unsafe{ intrinsics::init()};
        println!("{}", t); // Error at this line
}

$ rustc mem.rs
$ ./mem
Illegal instruction: 4

why?

答案:

11:33 < Dragon> hello, I got a runtime error: Illegal instruction: 4, can any one help me out? code

                snipet at http://my.oschina.net/zengsai/blog/360320

11:33  * Twisol shuffles over to the corner.

11:33 < Dragon> based on latest rustc

11:34 -!- chingucha [[email protected]] has quit [Ping timeout: 121 seconds]

11:34 < FreeFull> Dragon: That's because you're creating a null pointer dereference

11:35 < Dragon> FreeFull: how?

11:35 < FreeFull> When it's trying to print out the v field, specifically

11:35 < Twisol> Dragon: `unsafe{ intrinsics::init()}`

11:36 -!- nucleartide [[email protected]] has quit [Ping timeout: 121 seconds]

11:36 < FreeFull> References are meant to be never null, but you created a null reference with that

                  unsafe block, and tried to print it out

11:36 -!- chingucha [[email protected]] has joined #rust

11:36 < FreeFull> Printing a reference prints the data behind it

11:36 < Twisol> Dragon: `intrinsics::init()` creates a value initialized with all zeroes. Your data

                has a pointer in it, so that pointer gets set to 0.

11:36 < meh> shouldn't it segfault tho?

11:37 < Dragon> ok, i see , thanks FreeFull Twisol


你可能感兴趣的:(error,Rust)