Segmentation fault for array larger than 1022x1022

2019-09-05 04:47发布

I don't know Rust but I wanted to investigate the performance in scientific computing to compare it to Julia and Fortran. I managed to write the following program but the problem is that I get a runtime segmentation fault when MAX is larger than 1022. Any advice?

fn main() {
    const MAX: usize = 1023;
    let mut arr2: [[f64;  MAX];  MAX] = [[0.0;  MAX];  MAX]; 

    let pi: f64 = 3.1415926535;
    // compute something useless and put in matrix
    for ii in 0.. MAX {
        for jj in 0.. MAX {
            let i = ii as f64;
            let j = jj as f64;
            arr2[ii][jj] = ((i + j) * pi * 41.0).sqrt().sin();
        }
    }

let mut sum0:f64 = 0.0;

//collapse to scalar like sum(sum(array,1),2) in other langs
for iii in 0..MAX {
    let vec1:&[f64] = &arr2[iii][..];
    sum0 += vec1.iter().sum();
}
println!("this {}", sum0);
}

So no error just 'Segmentaion fault' in the terminal. I'm using Ubuntu 16 and installed with the command on www.rustup.rs. It is stable version rustc 1.12.1 (d4f39402a 2016-10-19).

1条回答
放我归山
2楼-- · 2019-09-05 05:38

You have a Stack Overflow (how ironic, hey?).

There are two solutions to the issue:

  1. Do not allocate a large array on the stack, use the heap instead (Vec)
  2. Only do so on a large stack.

Needless to say, using a Vec is just much easier; and you can use a Vec[f64; MAX] if you wish.

If you insist on using the stack, then I will redirect you to this question.

查看更多
登录 后发表回答