Large boxed array is stored in the stack?

I want to use Box to allocate large array in the heap. Here is my code snippet

fn main() {
    const N: usize = 10 * 1024 * 13;
    let b = Box::new([0u8; N]);
    println!("{:p}", b);
}

It outputs 0x7f96471cb010, which seems to be a stack address. Besides, when I let const N: usize = 10 * 1024 * 12, the same program outputs 0x55ecff8f99b0.

So why does this happen? Why is large boxed array stored in the stack?

That's just an assumption. It isn't.

Note that your code will first create the array on the stack and only then copy it into the heap allocation of the box. For sufficiently big arrays, this might cause a stack overflow at runtime. You should preferably create a vector instead and cast that to Box<[u8; N]>:

fn main() {
    const N: usize = 10 * 1024 * 1024;
    
    // this will overflow
    //let b = Box::new([0u8; N]);
    
    let b: Box<[u8; N]> = vec![0u8; N].try_into().unwrap();
    
    println!("{:p}", b);
}

Playground.

4 Likes

That may overflow, depending on optimization settings. It's a rather unfortunate situation.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.