gpt4 book ai didi

rust - 堆栈溢出堆缓冲区?

转载 作者:行者123 更新时间:2023-11-29 07:53:47 24 4
gpt4 key购买 nike

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

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;
}
}

但它会导致:

fatal runtime error: stack overflow

我在 OS X 10.11 和 Rust 1.12.0 上。

最佳答案

正如 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]);
}

您可以在以下问题中找到有关 boxBox::new() 之间区别的更多信息:What the difference is between using the box keyword and Box::new? .

关于rust - 堆栈溢出堆缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40035899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com