2

I am trying to initialize a large array with shape [[u64; 4096]; 64]. When I try to initialize this array with [[0; 4096]; 64] I get different results depending on how the program is run.

When I run with cargo test I get the following error:

thread '' has overflowed its stack
fatal runtime error: stack overflow

When I run with either cargo run or cargo test --release my program runs as expected. I think this means that the stack is simply not big enough to handle 8 * 64 * 4096 bytes (just over a MB), and that when I run in release or with cargo run a different sized stack is allocated for the program.

  • Is my assumption about running out of stack correct?
  • Could I allocate the array to the heap within a Box instead?
  • Is this the best option?

I would really like look ups for this array to be as fast as possible.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
BBS
  • 1,351
  • 2
  • 12
  • 27
  • the stack is only "faster" for allocation operation cause it's O(1), once you allocate the array on the heap, it will be as fast as any stack allocate object. Don't use big size array on the stack. – Stargateur Dec 31 '18 at 04:26
  • 1
    *a different sized stack is allocated for the program* — doubtful. More likely the optimizer has just completely thrown away all your code because it's never used. However, you neglected to provide any code. – Shepmaster Dec 31 '18 at 14:41

1 Answers1

3

Once you declare a variable in local scope, it is held on the stack. Since your stack capacity is not enough for the variable you declare, then you get a stack overflow error. I suggest to take a quick look at the book's section on the stack and the heap.

In such big sized objects, declaring them inside a Box makes them stored on the heap, which may be the wiser option for you.

Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68