Error code E0793
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:
ⓘ
Creating a reference to an insufficiently aligned packed field is
undefined behavior and therefore disallowed. Using an unsafe
block does not
change anything about this. Instead, the code should do a copy of the data in
the packed field or use raw pointers and unaligned accesses.
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.
ⓘ
Additional information
Note that this error is specifically about references to packed fields. Direct by-value access of those fields is fine, since then the compiler has enough information to generate the correct kind of access.
See issue #82523 for more information.