Skip to content

Commit 23d3ff1

Browse files
committed
Fix zero-size uninitialized boxes
Requesting a zero-size allocation is not allowed, return a dangling pointer instead. CC #63291 (comment)
1 parent 421bd77 commit 23d3ff1

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

src/liballoc/boxed.rs

+14-4
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,9 @@ impl<T> Box<T> {
141141
/// ```
142142
#[unstable(feature = "new_uninit", issue = "63291")]
143143
pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
144+
if mem::size_of::<T>() == 0 {
145+
return Box(NonNull::dangling().into())
146+
}
144147
let layout = alloc::Layout::new::<mem::MaybeUninit<T>>();
145148
let ptr = unsafe {
146149
Global.alloc(layout)
@@ -181,10 +184,17 @@ impl<T> Box<[T]> {
181184
/// ```
182185
#[unstable(feature = "new_uninit", issue = "63291")]
183186
pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
184-
let layout = alloc::Layout::array::<mem::MaybeUninit<T>>(len).unwrap();
185-
let ptr = unsafe { alloc::alloc(layout) };
186-
let unique = Unique::new(ptr).unwrap_or_else(|| alloc::handle_alloc_error(layout));
187-
let slice = unsafe { slice::from_raw_parts_mut(unique.cast().as_ptr(), len) };
187+
let ptr = if mem::size_of::<T>() == 0 || len == 0 {
188+
NonNull::dangling()
189+
} else {
190+
let layout = alloc::Layout::array::<mem::MaybeUninit<T>>(len).unwrap();
191+
unsafe {
192+
Global.alloc(layout)
193+
.unwrap_or_else(|_| alloc::handle_alloc_error(layout))
194+
.cast()
195+
}
196+
};
197+
let slice = unsafe { slice::from_raw_parts_mut(ptr.as_ptr(), len) };
188198
Box(Unique::from(slice))
189199
}
190200
}

0 commit comments

Comments
 (0)