Skip to content

Commit

Permalink
Clarify initialized union may contain uninited bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
hehaoqian committed Aug 3, 2023
1 parent 2a8068e commit f9e4a01
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/items/unions.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,27 @@ struct fields:
let f = unsafe { u.f1 };
```

## Uninitialized bytes in initialized union

Initialized union may contain uninitialized bytes,
if its initialized field does not cover all bytes of union:

```rust
#[repr(C)]
union Foo {
int32: i32,
int64: i64,
}

unsafe {
let foo = Foo { int32: 1 };
// Low 4 bytes are initialized,
// but high 4 bytes are not,
// so each execution may print different result.
println!("{}", foo.int64);
}
```

## Reading and writing union fields

Unions have no notion of an "active field". Instead, every union access just
Expand Down

0 comments on commit f9e4a01

Please sign in to comment.