I am trying to convert a C++ program to Rust. Everything works as expected, except for a certain variable which is a huge multidimensional array which gives a stack overflow in Rust (but not in C++). How do you overcome this?
Rust array types like
[u8; 100] (and their multi-dimensional combinations) will be stored on stack, and copied around when you pass it to functions, so they are very likely to overflow the stack.
Vec instead. It is heap allocated, so it doesn't use the stack.
For multi-dimensional "arrays" you don't need
Vec<Vec<u8>> (also known as "jagged array"). It's better to use
Vec only for the outermost type, and then use arrays inside, like
Vec<[u8; 100]> for 2d array, and
Vec<[[u8; 100]; 100]> for 3d array.
If you do some serious processing on multi-dimensional arrays, check out
Correct me if I'm wrong, but won't the (sub) arrays when inserting into the vec also be stored on the stack first?
At least for methods like
push_back and similar I think this does not solve the problem when working with "giant" multidimensional arrays.
I had the same problem once and tried getting it on the heap using
Box without having it on the stack beforehand. Sadly I can't seem to find the thread right now..
If you create the vector using the
vec! macro, then no, the sub arrays won't be temporarily stored on the stack. As for adding more arrays with
push, this might be an issue, but you may be able to avoid it by calling
I'll try with ndarrays. Thanks.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.