Stack overflow with heap buffer?

2020-04-08 11:33发布

I have the following code to read from a file:

let mut buf: Box<[u8]> = Box::new([0; 1024 * 1024]);
while let Ok(n) = f.read(&mut buf) {
    if n > 0 {
        resp.send_data(&buf[0..n]);
    } else {
        break;
    }
}

But it causes:

fatal runtime error: stack overflow

I am on OS X 10.11 with Rust 1.12.0.

标签: rust
1条回答
Explosion°爆炸
2楼-- · 2020-04-08 12:07

As Matthieu said, Box::new([0; 1024 * 1024]) will currently overflow the stack due to initial stack allocation. If you are using Rust Nightly, the box_syntax feature will allow it to run without issues:

#![feature(box_syntax)]

fn main() {
    let mut buf: Box<[u8]> = box [0; 1024 * 1024]; // note box instead of Box::new()

    println!("{}", buf[0]);
}

You can find additional information about the difference between box and Box::new() in the following question: What the difference is between using the box keyword and Box::new?.

查看更多
登录 后发表回答