diff options
| author | Stuart Cook <Zalathar@users.noreply.github.com> | 2025-08-15 16:16:32 +1000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-08-15 16:16:32 +1000 |
| commit | b955aa722e190689740e6379eee9684c324e8d1f (patch) | |
| tree | 50abb950a14d4841200c32bed69374751f06e4af | |
| parent | 44eb7a167c9df395c803bf113a933f668b4c278a (diff) | |
| parent | 57901fe09242582608dfbaa047ea006cf0c984a2 (diff) | |
| download | rust-b955aa722e190689740e6379eee9684c324e8d1f.tar.gz rust-b955aa722e190689740e6379eee9684c324e8d1f.zip | |
Rollup merge of #144944 - He1pa:E0793, r=compiler-errors
E0793: Clarify that it applies to unions as well pick up inactive PR: https://github.com/rust-lang/rust/pull/131472 Also: Adjust the language slightly to be more consistent with other similar messages (was created instead of got created). Add a short section on union. Add an example line showing referencing a field in a packed struct is safe if the field's type isn't more strictly aligned than the pack. r? compiler-errors
| -rw-r--r-- | compiler/rustc_error_codes/src/error_codes/E0793.md | 34 |
1 files changed, 33 insertions, 1 deletions
diff --git a/compiler/rustc_error_codes/src/error_codes/E0793.md b/compiler/rustc_error_codes/src/error_codes/E0793.md index ccd1b43bd19..2722dac104b 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0793.md +++ b/compiler/rustc_error_codes/src/error_codes/E0793.md @@ -1,4 +1,9 @@ -An unaligned reference to a field of a [packed] struct got created. +An unaligned reference to a field of a [packed] `struct` or `union` was created. + +The `#[repr(packed)]` attribute removes padding between fields, which can +cause fields to be stored at unaligned memory addresses. Creating references +to such fields violates Rust's memory safety guarantees and can lead to +undefined behavior in optimized code. Erroneous code example: @@ -45,9 +50,36 @@ unsafe { // For formatting, we can create a copy to avoid the direct reference. let copy = foo.field1; println!("{}", copy); + // Creating a copy can be written in a single line with curly braces. // (This is equivalent to the two lines above.) println!("{}", { foo.field1 }); + + // A reference to a field that will always be sufficiently aligned is safe: + println!("{}", foo.field2); +} +``` + +### Unions + +Although creating a reference to a `union` field is `unsafe`, this error +will still be triggered if the referenced field is not sufficiently +aligned. Use `addr_of!` and raw pointers in the same way as for struct fields. + +```compile_fail,E0793 +#[repr(packed)] +pub union Foo { + field1: u64, + field2: u8, +} + +unsafe { + let foo = Foo { field1: 0 }; + // Accessing the field directly is fine. + let val = foo.field1; + + // A reference to a packed union field causes an error. + let val = &foo.field1; // ERROR } ``` |
