Stack overflow with heap buffer?

前端 未结 1 1507
醉梦人生
醉梦人生 2021-01-19 15:29

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 &         


        
1条回答
  •  醉梦人生
    2021-01-19 16:26

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

    0 讨论(0)
提交回复
热议问题