rust-memory-model: Is it undefined behavior to hold an invalid reference, if it is never dereferenced.

It is not Safe in rust code to create invalid references, in that these references can be used by safe code to trigger Undefined Behavior, however, is it Undefined Behavior to create one of these references?

For example, does this code trigger Undefined Behavior?

struct Foo {...}
let _x: &const Foo = &*(1024 as *const Foo);

How about this code, which gets the address of the member, but does no reading?

struct Foo {
    member: i32
}
let _x: &i32 = &(*(1024 as *const Foo)).member;

How about this code, which creates an invalid reference by over-extending the lifetime, but does not follow it?

struct Foo {...}
let _x: &'static Foo;
{
    let y = Foo {...};
    _x = mem::transmute(&y);
}

Or this code, which creates a reference with the wrong lifetime, but only follows it while the object behind it is still alive?

struct Foo {
    member: i32
}
let y: &'static Foo;
{
    let x = Foo {...};
    y = mem::transmute(&x);
    println!("y.member = {}", y.member);
}

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 45 (9 by maintainers)

Most upvoted comments

@ubsan

First, at least for nonnull/range that’s how LLVM works, so we don’t have much of a choice.

Also, what’s the problem with that idea?