堆栈溢出堆缓冲区?

Ele*_*Ent 4 rust

我有以下代码从文件中读取:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它导致:

fatal runtime error: stack overflow
Run Code Online (Sandbox Code Playgroud)

我在OS X 10.11上使用Rust 1.12.0.

lje*_*drz 5

正如Matthieu所说,Box::new([0; 1024 * 1024])由于初始堆栈分配,目前将溢出堆栈.如果您使用Rust Nightly,该box_syntax功能将允许它运行没有问题:

#![feature(box_syntax)]

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

    println!("{}", buf[0]);
}
Run Code Online (Sandbox Code Playgroud)

您可以找到有关之间的区别更多的信息box,并Box::new()在以下问题:不同的是用盒子关键字和Box ::新之间是什么?.