Stack overflow with heap buffer?

爱⌒轻易说出口 提交于 2020-01-11 09:25:08

问题


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.


回答1:


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?.



来源:https://stackoverflow.com/questions/40035899/stack-overflow-with-heap-buffer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!