Borrow checker unsoundness with unions · Issue #45157 · rust-lang/rust (original) (raw)

Skip to content

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Appearance settings

@petrochenkov

Description

@petrochenkov

#![allow(unused)]

#[derive(Clone, Copy, Default)] struct S { a: u8, b: u8, } #[derive(Clone, Copy, Default)] struct Z { c: u8, d: u8, }

union U { s: S, z: Z, }

fn main() { unsafe { let mut u = U { s: Default::default() };

let mref = &mut u.s.a;
let err = &u.z.c; // This line compiles, but it certainly shouldn't ...
drop(mref); // ... (at least if `mref` is used after `err`)

}}

"Cousins" of borrowed union sub-fields (and their further children) are not marked as borrowed.
The same bug should happen with move checking as well, but I haven't made an example yet.