Is zeroing a repr(Rust) enum UB?

Correct.

The current implementation does more optimizations, but they should not be relied upon.

Here's a quick UB example:

#[derive(Debug)]
enum Foo { A = 1, B = 2 }

fn main() {
    let x: Option<Foo> = unsafe { std::mem::transmute(0_u8) };
    dbg!(x);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a86270a4f0d74f55d1655a1d4a984f2b

Error from miri:

error: Undefined Behavior: type validation failed at .<enum-variant(Some)>.0.<enum-tag>: encountered 0x00, but expected a valid enum tag
 --> src/main.rs:5:35
  |
5 |     let x: Option<Foo> = unsafe { std::mem::transmute(0_u8) };
  |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed at .<enum-variant(Some)>.0.<enum-tag>: encountered 0x00, but expected a valid enum tag
  |
  = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
  = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
1 Like