|
62 | 62 | //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
|
63 | 63 | //! [`Global`] allocator with [`Layout::for_value(&*value)`].
|
64 | 64 | //!
|
| 65 | +//! For zero-sized values, the `Box` pointer still has to be [valid] for reads |
| 66 | +//! and writes and sufficiently aligned. In particular, casting any aligned |
| 67 | +//! non-zero integer literal to a raw pointer produces a valid pointer, but a |
| 68 | +//! pointer pointing into previously allocated memory that since got freed is |
| 69 | +//! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot |
| 70 | +//! be used is to use [`ptr::NonNull::dangling`]. |
| 71 | +//! |
65 | 72 | //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
|
66 | 73 | //! as a single pointer and is also ABI-compatible with C pointers
|
67 | 74 | //! (i.e. the C type `T*`). This means that if you have extern "C"
|
|
125 | 132 | //! [`Global`]: crate::alloc::Global
|
126 | 133 | //! [`Layout`]: crate::alloc::Layout
|
127 | 134 | //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
|
| 135 | +//! [valid]: ptr#safety |
128 | 136 |
|
129 | 137 | #![stable(feature = "rust1", since = "1.0.0")]
|
130 | 138 |
|
@@ -530,7 +538,10 @@ impl<T: ?Sized> Box<T> {
|
530 | 538 | /// memory problems. For example, a double-free may occur if the
|
531 | 539 | /// function is called twice on the same raw pointer.
|
532 | 540 | ///
|
| 541 | + /// The safety conditions are described in the [memory layout] section. |
| 542 | + /// |
533 | 543 | /// # Examples
|
| 544 | + /// |
534 | 545 | /// Recreate a `Box` which was previously converted to a raw pointer
|
535 | 546 | /// using [`Box::into_raw`]:
|
536 | 547 | /// ```
|
|
0 commit comments