0

I know arrays are in the stack by default, so I'm boxing it, but I still get a segfault if the size of it is too big.

How can I fix the problem and why will my program segfault if the size of the array is 5 million?

extern crate rand;                                                                                                                                                                                                  
use rand::Rng;

fn main() {
    const SIZE: usize = 500000; // segfaut if SIZE is 5 million
    let mut v: Box<[i32; SIZE]> = Box::new([0; SIZE]);
    let mut i = 0;
    while i < SIZE {
        let mut rng = rand::thread_rng();
        if rng.gen() {
            v[i] = 1;
        }
        i = i + 1;
    }   
    i = 0;
    let mut sum = 0;
    while i < SIZE {
        sum = sum + v[i];
        i = i + 1;
    }   
    println!("Total number is {}", SIZE);
    println!("number of 1 is {}", sum);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
echo
  • 2,666
  • 1
  • 25
  • 17
  • Why do you have 30 lines of code when 3 will do? `fn main() { let _v = Box::new([0i32; 5_000_000]); }`. – Shepmaster Dec 03 '16 at 23:33
  • I am learning rust. This is a contrived example. – echo Dec 03 '16 at 23:37
  • FWIW, I'd [write the code like this](http://play.integer32.com/?gist=ac8e61e86bf71ab7c8bb106c1e0af0d1&version=stable). – Shepmaster Dec 03 '16 at 23:44
  • Vec is the way to go. What if I want to create a large array in heap? Is it possible in rust? – echo Dec 03 '16 at 23:52
  • 1
    No, not right now. I added another answer to the duplicate for future Rust. However, a `Vec` is going to be basically the same in 99.99% of the cases, so it's highly recommended to use it. – Shepmaster Dec 04 '16 at 00:03

0 Answers0