Skip to content

Commit e8f09a4

Browse files
committed
add examples
1 parent be589ef commit e8f09a4

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

src/behavior-considered-undefined.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,22 @@ r[undefined.validity.const-provenance]
223223

224224
This implies that transmuting or otherwise reinterpreting a pointer (reference, raw pointer, or function pointer) into a non-pointer type (such as integers) is undefined behavior if the pointer had provenance.
225225

226+
> [!EXAMPLE]
227+
> All of the following are UB:
228+
> ```rust
229+
> const REINTERPRET_PTR_AS_INT: usize = {
230+
> let ptr = &0;
231+
> unsafe { (&raw const ptr as *const usize).read() }
232+
> };
233+
>
234+
> const PTR_BYTES_IN_WRONG_ORDER: &i32 = {
235+
> let mut ptr = &0;
236+
> let ptr_bytes = &raw mut ptr as *mut std::mem::MaybeUninit::<u8>;
237+
> unsafe { std::ptr::swap(ptr_bytes.add(1), ptr_bytes.add(2)) };
238+
> ptr
239+
> };
240+
> ```
241+
226242
r[undefined.validity.undef]
227243
**Note:** Uninitialized memory is also implicitly invalid for any type that has
228244
a restricted set of valid values. In other words, the only cases in which

0 commit comments

Comments
 (0)