堆缓冲区溢出? [英] Stack overflow with heap buffer?

查看:110
本文介绍了堆缓冲区溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但它会导致:

fatal runtime error: stack overflow

我使用的是带有 Rust 1.12.0 的 OS X 10.11.

I am on OS X 10.11 with Rust 1.12.0.

推荐答案

正如 Matthieu 所说,Box::new([0; 1024 * 1024]) 当前会因为初始堆栈而溢出堆栈分配.如果您使用 Rust Nightly,box_syntax 功能将允许它运行而不会出现问题:

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

您可以在以下问题中找到有关 boxBox::new() 之间区别的更多信息:使用 box 关键字和 Box::new 有什么区别?.

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

这篇关于堆缓冲区溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆