File tree Expand file tree Collapse file tree 1 file changed +33
-1
lines changed
compiler/rustc_error_codes/src/error_codes Expand file tree Collapse file tree 1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change 1
- An unaligned reference to a field of a [ packed] struct got created.
1
+ An unaligned reference to a field of a [ packed] ` struct ` or ` union ` was created.
2
+
3
+ The ` #[repr(packed)] ` attribute removes padding between fields, which can
4
+ cause fields to be stored at unaligned memory addresses. Creating references
5
+ to such fields violates Rust's memory safety guarantees and can lead to
6
+ undefined behavior in optimized code.
2
7
3
8
Erroneous code example:
4
9
@@ -45,9 +50,36 @@ unsafe {
45
50
// For formatting, we can create a copy to avoid the direct reference.
46
51
let copy = foo.field1;
47
52
println!("{}", copy);
53
+
48
54
// Creating a copy can be written in a single line with curly braces.
49
55
// (This is equivalent to the two lines above.)
50
56
println!("{}", { foo.field1 });
57
+
58
+ // A reference to a field that will always be sufficiently aligned is safe:
59
+ println!("{}", foo.field2);
60
+ }
61
+ ```
62
+
63
+ ### Unions
64
+
65
+ Although creating a reference to a ` union ` field is ` unsafe ` , this error
66
+ will still be triggered if the referenced field is not sufficiently
67
+ aligned. Use ` addr_of! ` and raw pointers in the same way as for struct fields.
68
+
69
+ ``` compile_fail,E0793
70
+ #[repr(packed)]
71
+ pub union Foo {
72
+ field1: u64,
73
+ field2: u8,
74
+ }
75
+
76
+ unsafe {
77
+ let foo = Foo { field1: 0 };
78
+ // Accessing the field directly is fine.
79
+ let val = foo.field1;
80
+
81
+ // A reference to a packed union field causes an error.
82
+ let val = &foo.field1; // ERROR
51
83
}
52
84
```
53
85
You can’t perform that action at this time.
0 commit comments