Stack overflow with heap buffer?

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 this causes:

fatal runtime error: stack overflow

I'm on OS X 10.11 with Rust 1.12.0.

+4
source share
1 answer

As Mattiu said, the Box::new([0; 1024 * 1024])stack will overflow due to the initial stack allocation. If you use Rust Nightly, the function box_syntaxallows you to run without problems:

#![feature(box_syntax)]

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

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

Further information on the difference between boxand Box::new()can be found in the following question: What is the difference between using the box and Box :: new keywords? .

+5
source

Source: https://habr.com/ru/post/1657711/


All Articles