How does 'Box' work when 'malloc' returns a null pointer?

Hello :crab:,

I read an article about the importance of null-pointer checking return values of malloc/realloc/calloc functions in C and C++ (these functions return a null-pointer when they fail to allocate the requested amount of memory).

Now, I want to see how Box<T>::new(x: T) works when the underlying memory allocator fails to allocate memory.

impl<T> Box<T> {
    /// Allocates memory on the heap and then places `x` into it.
    /// This doesn't actually allocate if `T` is zero-sized.
    /// # Examples
    /// ```
    /// let five = Box::new(5);
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new(x: T) -> Box<T> {
        box x

Unfortunately, the source code for function Box<T>::new(x: T) seems to not unveil what happens behind the curtains. I'm not sure where to look to learn how box x works..

#[stable(feature = "global_alloc", since = "1.28.0")]
pub unsafe fn alloc(layout: Layout) -> *mut u8 {
    __rust_alloc(layout.size(), layout.align())

The function alloc::alloc::alloc doesn't seem to perform any exception checking for null-pointers..

I'm stuck here, and don't know where else to look for more info :cry:
Can anyone give some pointers on where to look for info on how Box<T> works when the underlying memory allocator returns a null pointer?

Thank you for reading !!

If box fails to allocate it usually aborts with handle_alloc_error

Edit: handle_alloc_error usually aborts

1 Like

The code to compile box x is, I believe, located here:

This generates a call to the exchange_malloc lang item, which in liballoc is defined here:

As naim mentioned, it checks the result from alloc and calls handle_alloc_error on failure.


Just to clarify, by default it is an abort, not a panic (so it can not be caught).


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.