Skip to content

Commit 2e0ca94

Browse files
committed
add a concrete example
1 parent f6247ff commit 2e0ca94

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

Diff for: library/core/src/intrinsics.rs

+14-5
Original file line numberDiff line numberDiff line change
@@ -2550,14 +2550,23 @@ pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize) {
25502550
///
25512551
/// * `dst` must be properly aligned.
25522552
///
2553-
/// Additionally, note that changing `*dst` in this way can lead to undefined behavior later if the
2554-
/// written bytes are not a valid representation of some `T`. For instance, if `dst: *mut bool`, a
2555-
/// `dst.write_bytes(0xFFu8, 1)` followed by `dst.read()` is undefined behavior since the `read`
2556-
/// tries to construct a `bool` value from `0xFF` which does not represent any `bool`.
2557-
///
25582553
/// Note that even if the effectively copied size (`count * size_of::<T>()`) is
25592554
/// `0`, the pointer must be non-null and properly aligned.
25602555
///
2556+
/// Additionally, note that changing `*dst` in this way can easily lead to undefined behavior (UB)
2557+
/// later if the written bytes are not a valid representation of some `T`. For instance, the
2558+
/// follwing is an **incorrect** use of this function:
2559+
///
2560+
/// ```rust,no_run
2561+
/// unsafe {
2562+
/// let mut value: u8 = 0;
2563+
/// let ptr: *mut bool = &mut value as *mut u8 as *mut bool;
2564+
/// let _bool = ptr.read(); // This is fine, `ptr` points to a valid `bool`.
2565+
/// ptr.write_bytes(42u8, 1); // This function itself does not cause UB...
2566+
/// let _bool = ptr.read(); // ...but it makes this operation UB! ⚠️
2567+
/// }
2568+
/// ```
2569+
///
25612570
/// [valid]: crate::ptr#safety
25622571
///
25632572
/// # Examples

0 commit comments

Comments
 (0)