about summary refs log tree commit diff
diff options
context:
space:
mode:
authorRalf Jung <post@ralfj.de>2022-07-09 10:48:43 -0400
committerRalf Jung <post@ralfj.de>2022-07-09 10:48:43 -0400
commit2e0ca9472ba3ec1532bb752f7ea1f477f8c34c90 (patch)
tree96aaf5779f927e5bbb176933849e38ed0abd3c0a
parentf6247ffa5afb29fd86d54db8062ff031daa10555 (diff)
downloadrust-2e0ca9472ba3ec1532bb752f7ea1f477f8c34c90.tar.gz
rust-2e0ca9472ba3ec1532bb752f7ea1f477f8c34c90.zip
add a concrete example
-rw-r--r--library/core/src/intrinsics.rs19
1 files changed, 14 insertions, 5 deletions
diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs
index 4c8619f3135..d7ed82e71b6 100644
--- a/library/core/src/intrinsics.rs
+++ b/library/core/src/intrinsics.rs
@@ -2550,14 +2550,23 @@ pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize) {
 ///
 /// * `dst` must be properly aligned.
 ///
-/// Additionally, note that changing `*dst` in this way can lead to undefined behavior later if the
-/// written bytes are not a valid representation of some `T`. For instance, if `dst: *mut bool`, a
-/// `dst.write_bytes(0xFFu8, 1)` followed by `dst.read()` is undefined behavior since the `read`
-/// tries to construct a `bool` value from `0xFF` which does not represent any `bool`.
-///
 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is
 /// `0`, the pointer must be non-null and properly aligned.
 ///
+/// Additionally, note that changing `*dst` in this way can easily lead to undefined behavior (UB)
+/// later if the written bytes are not a valid representation of some `T`. For instance, the
+/// follwing is an **incorrect** use of this function:
+///
+/// ```rust,no_run
+/// unsafe {
+///     let mut value: u8 = 0;
+///     let ptr: *mut bool = &mut value as *mut u8 as *mut bool;
+///     let _bool = ptr.read(); // This is fine, `ptr` points to a valid `bool`.
+///     ptr.write_bytes(42u8, 1); // This function itself does not cause UB...
+///     let _bool = ptr.read(); // ...but it makes this operation UB! ⚠️
+/// }
+/// ```
+///
 /// [valid]: crate::ptr#safety
 ///
 /// # Examples