Peculiar behavior when doing bad things

Because otherwise any reference could be a null pointer and dereferencing one wouldn't be safe at all. So you would need to use unsafe for accessing references, which goes againt the whole point of references: they are safe to use and always points to a valid object.

This argument only explains why a null-reference would not be allowed to be exposed to arbitrary safe code, e. g. returned by a non-unsafe function. The restriction is however stronger than that. It's sililar to how bool must not be anything other than the byte 0 or 1; it allows for optimizations that can assume that references aren't zero, even for cases when they are never dereferenced. One example of such an optimization is given in a previous post in this thread.

3 Likes

However, this code does not generate an illegal instruction, despite the reference being null.


fn main() {
    let m: &usize = unsafe { std::mem::transmute(0u64) };
    println!("Hello, world, ref is {}!", m as *const _ as usize);
}

Hmm... I take that back! It does generate an illegal instruction when built with release!

Should this thread be on users.rust-lang.org? This seems like a general thread about using Rust, not about the development of Rust itself.

2 Likes

The effects of undefined behavior are... undefined. It may or may not do something obvious.

7 Likes

Recent and very relevant: Undefined Behavior deserves a better reputation | SIGPLAN Blog

TL;DR: UB is a binding promise from the programmer to the compiler that something will never happen. The compiler then uses that axiom in order to optimize the program (an easy example being dead branch elimination).

6 Likes