Hi,
I was struggling in solving an exercise on adventofcode, filling a Nim array with complex structures. I had a segmentation fault, and I wanted to check my code (especially the instantiation of nested arrays) using a simple test code.
This is the code:
const
H = 1000
W = 1000
type myArray = array[H, array[W, int]]
proc fillArray(): myArray =
echo "Instanciating..."
var a: myArray
echo "OK!"
for h in 0..H:
for w in 0..W:
a[h][w] = 1
result = a
proc main() =
echo "Calling fillArray procedure..."
let a : myArray = fillArray()
when isMainModule:
main()
According to the Nim documentation (I don't remember if it was on Nim by Example, or in the Nim manual), but var a: myArray instanciates by itself the nested array. This code produces also or a segmentation fault error:
Calling fillArray procedure... │~
[1] 15746 segmentation fault (core dumped) ./nim_test
According to this output, "something" happened at the fillArray procedure call (as the first echo statement has not been executed... I think). I will try to debug the code using gdb or something, but I would be grateful if someone has a clear explanation/documentation to provide me, in order to explain the behaviour (and the mistake I did).
Btw, I use the last version of Nim: 0.19.0.
Thanks in advance, and best wishes for the end of this year.
for h in 0..H:
for w in 0..W:
This is the source of your error — you're trying to do something at positions H and W, and your array has H elements: from 0 to H-1.
To fix it, use ..< which excludes upper limit:
for h in 0 ..< H:
for w in 0 ..< W:
To play it safe, the loop indices can be limited like this:
for h in 0..a.high:
for w in 0..a[h].high:
This works no matter what size the arrays are.Thank you all for your replies. I was thinking actually about the size of the array, but I didn't know there is a "limited" size for a given array... As a array is instantiated in the stack, so it depends of the size of the stack, right? Is there a "standard" limit or Nim handles his own limit to implement a nested array?
Thanks you again :)