From: Ralf Jung Date: Fri, 16 Aug 2024 05:50:56 +0000 (+0200) Subject: add link to stabilization PR and explain why the code has UB X-Git-Url: https://git.ralfj.de/web.git/commitdiff_plain/cce7a39d255170e4315c5da78949491e07c1c1f9?ds=sidebyside add link to stabilization PR and explain why the code has UB --- diff --git a/personal/_posts/2024-08-14-places.md b/personal/_posts/2024-08-14-places.md index 912f7d5..8f3532c 100644 --- a/personal/_posts/2024-08-14-places.md +++ b/personal/_posts/2024-08-14-places.md @@ -11,6 +11,7 @@ However, when it comes to unsafe code, a proper understanding of this dichotomy Consider the following [example](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=9a8802d20da16d6569510124c5827794): ```rust +// As a "packed" struct, this type has alignment 1. #[repr(packed)] struct MyStruct { field: i32 @@ -21,10 +22,12 @@ let ptr = &raw const x.field; // This line is fine. let ptr_copy = &raw const *ptr; // But this line has UB! +// `ptr` is a pointer to `i32` and thus requires 4-byte alignment on +// memory accesses, but `x` is just 1-aligned. let val = *ptr; ``` -Here I am using the unstable but soon-to-be-stabilized "raw borrow" operator, `&raw const`. +Here I am using the unstable but [soon-to-be-stabilized](https://github.com/rust-lang/rust/pull/127679) "raw borrow" operator, `&raw const`. You may know it in its stable form as a macro, `ptr::addr_of!`, but the `&` syntax makes the interplay of places and values more explicit so we will use it here. The last line has Undefined Behavior (UB) because `ptr` points to a field of a packed struct, which is not sufficiently aligned.