There is already a question for this but related to Rust 0.13 and the syntax seems to have changed. From the current documentation I understood that creating an array on the heap would be something like this:
fn main() {
const SIZE: usize = 1024 * 1024;
Box::new([10.0; SIZE]);
}
But when I run this program I get the following error:
thread '<main>' has overflowed its stack
What am I doing wrong?
The problem is that the array is being passed to the
Box::new
function as an argument, which means it has to be created first, which means it has to be created on the stack.You're asking the compiler to create 8 megabytes of data on the stack: that's what's overflowing it.
The solution is to not use a fixed-size array at all, but a
Vec
. The simplest way I can think of to make aVec
of 8 million10.0
is this:Or, if for some reason you'd rather use iterators:
This should only perform a single heap allocation.
Note that you can subsequently take a
Vec
and turn it into aBox<[_]>
by using theinto_boxed_slice
method.See also: