Skip to content

Commit 2ec4cf4

Browse files
authored
UB-check for alignment of ptr to Box::from_raw{,_in}
1 parent 28b83ee commit 2ec4cf4

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

library/alloc/src/boxed.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -1017,7 +1017,7 @@ impl<T: ?Sized> Box<T> {
10171017
/// resulting `Box`. Specifically, the `Box` destructor will call
10181018
/// the destructor of `T` and free the allocated memory. For this
10191019
/// to be safe, the memory must have been allocated in accordance
1020-
/// with the [memory layout] used by `Box` .
1020+
/// with the [memory layout] used by `Box`.
10211021
///
10221022
/// # Safety
10231023
///
@@ -1166,8 +1166,13 @@ impl<T: ?Sized, A: Allocator> Box<T, A> {
11661166
#[unstable(feature = "allocator_api", issue = "32838")]
11671167
#[rustc_const_unstable(feature = "const_box", issue = "92521")]
11681168
#[inline]
1169-
pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1170-
Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1169+
pub const unsafe fn from_raw_in(ptr: *mut T, alloc: A) -> Self {
1170+
ub_checks::assert_unsafe_precondition!(
1171+
check_language_ub,
1172+
"Box::from_raw_in requires that the pointer is properly aligned",
1173+
(ptr: *mut () = ptr as *mut (), align: usize = align_of::<T>()) => ptr.is_aligned_to(align)
1174+
);
1175+
Box(unsafe { Unique::new_unchecked(ptr) }, alloc)
11711176
}
11721177

11731178
/// Constructs a box from a `NonNull` pointer in the given allocator.

0 commit comments

Comments
 (0)