4

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ElefEnt
  • 2,027
  • 1
  • 16
  • 20

1 Answers1

5

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

Community
  • 1
  • 1
ljedrz
  • 20,316
  • 4
  • 69
  • 97
  • 1
    Will it really overflow the stack? I mean, it's only 1MB, which is not THAT much. I know some OSes have tight limits by default, but I don't know if OS X is one of them. – Matthieu M. Oct 14 '16 at 08:37
  • Well, that is the error that is reported; perhaps it is bogus, but I'm not sure how to investigate it further. – ljedrz Oct 14 '16 at 08:47