Open
Description
The following code will segfault on playground due to stack overflow:
fn do_stuff() {
let data = [0; 10000000];
}
The problem is that Rust arrays are created on the stack, but this array is too large to fit on the stack.
What's worse, the naive solution doesn't work either:
fn do_stuff() {
let data = Box::new([0; 10000000]);
}
This still instantiates the array on the stack and segfaults. The proper solution is this:
fn do_stuff() {
let data = vec![0; 10000000].into_boxed_slice();
}
This issue is particularly tricky if the array size is dynamic, and does not typically manifest on tests, resulting in unexpected crashes in production. Example:
fn do_stuff(len: usize) {
let data = [0; len];
}
Here len
can be set to an arbitrarily large number that would overflow the stack. Only length values of types u8
, i8
, u16
, i16
are definitely safe. The solution is to use one of them or create the array on the heap as described above.