I wanted a big array on the heap, so I wrote
Box::new(array). But the array is built on the
stack first, and only then moved to the heap. With a
big enough array that is a stack overflow.
What happens
For my 1BRC hash table I needed an array of 16,384 slots, 512 KB:
slots: Box::new(std::array::from_fn(|_| Slot::default())),
Box::new is an ordinary function. Rust first builds its
argument, the whole array, and only then calls Box::new,
which copies it to the heap (the same rule as in #0001). So for a moment
the whole array is on the stack.
And the stack is small: a new thread gets only 2 MB. Tests run on such threads too.
Does it matter?
In a release build the compiler usually skips the copy and builds the
array straight on the heap. In a debug build, which
cargo test uses, it doesn't, and the array even ends up on
the stack several times. How big does the array have to be? I tried it
in a small test project:
| Array size | cargo test |
cargo test --release |
|---|---|---|
| 384 KB | ok | ok |
| 512 KB | stack overflow | ok |
| 2 MB | stack overflow | ok |
thread 'tests::box_new_512k' has overflowed its stack
fatal runtime error: stack overflow, aborting
So the program can work fine and only the tests crash. That makes it hard to spot.
The fix
Build the array where it belongs, on the heap, with a
Vec, and then turn it into a box:
let slots: Box<[Slot; SLOTS]> = (0..SLOTS)
.map(|_| Slot::default())
.collect::<Vec<_>>() // built right on the heap
.into_boxed_slice() // Box<[Slot]>, no copy
.try_into() // Box<[Slot; SLOTS]>, checks the length
.ok().unwrap();
The array never touches the stack. This way even 64 MB works in a debug build.
Why .ok().unwrap()? A plain .unwrap() needs
Slot to implement Debug, so that it can print
the error. .ok() drops the error, so it works without it.
Adding #[derive(Debug)] to Slot works too.
Rule: a big array that should live on the heap must
not be built as a value first. Go through a Vec.