Skip to content

Commit 82ccdf7

Browse files
committed
channel: Handle possible allocation failure in list::Block::new.
1 parent d2c53ef commit 82ccdf7

1 file changed

Lines changed: 10 additions & 3 deletions

File tree

  • crossbeam-channel/src/flavors

crossbeam-channel/src/flavors/list.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Unbounded channel implemented as a linked list.
22
3-
use std::alloc::{alloc_zeroed, Layout};
3+
use std::alloc::{alloc_zeroed, handle_alloc_error, Layout};
44
use std::boxed::Box;
55
use std::cell::UnsafeCell;
66
use std::marker::PhantomData;
@@ -74,15 +74,22 @@ struct Block<T> {
7474
impl<T> Block<T> {
7575
/// Creates an empty block.
7676
fn new() -> Box<Self> {
77+
let layout = Layout::new::<Self>();
78+
assert!(layout.size() != 0, "Block should never be zero-sized, as it has an AtomicPtr field");
79+
// SAFETY: layout is not zero-sized
80+
let ptr = unsafe { alloc_zeroed(layout) };
81+
// Handle allocation failure
82+
if ptr.is_null() {
83+
handle_alloc_error(layout)
84+
}
7785
// SAFETY: This is safe because:
7886
// [1] `Block::next` (AtomicPtr) may be safely zero initialized.
7987
// [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4].
8088
// [3] `Slot::msg` (UnsafeCell) may be safely zero initialized because it
8189
// holds a MaybeUninit.
8290
// [4] `Slot::state` (AtomicUsize) may be safely zero initialized.
8391
// TODO: unsafe { Box::new_zeroed().assume_init() }
84-
let layout = Layout::new::<Self>();
85-
unsafe { Box::from_raw(alloc_zeroed(layout).cast()) }
92+
unsafe { Box::from_raw(ptr.cast()) }
8693
}
8794

8895
/// Waits until the next pointer is set.

0 commit comments

Comments
 (0)