Array index out of bounds with arrays of structs
-
I've come across an odd issue with arrays of structs. I know there are a few other array-related bug reports but this one seems to be a bit different. I have included code to reproduce this.
If you fill an array with structs, then iterate over the array and put each element back at the same index, the game will crash "later" when accessing the array with this error (from the example code):
Array index out of bounds.
(Array size: 100, index: 100)The example code crashes after about 7 seconds. Here are a couple of other points:
- The more items in the array the faster the crash will occur.
- If use use an array of ints (or possibly any other primitive type) the crash will not occur.
- If you do not re-populate the array with its own items the crash will not occur.
This isn't an exact reproduction of what I was experiencing, but it seems to be roughly what was happening. The differences were:
- Fuze was crashing completely so I was getting no error message.
- I would only see the crash if I put a struct back into the array without changing it in any way. If I changed a value in the struct it would be fine.
Sample code:
struct testStruct int a int b endstruct list = [] testStruct object for i = 0 to 100 loop object.a = 1 object.b = 2 list[len(list)] = object repeat loop clear() print("Running...") // Iterate over the list, replacing each item with itself for i = 0 to len(list) loop item = list[i] list[i] = item repeat // Iterate over the list just referencing each item for i = 0 to len(list) loop if list[i] then endif repeat update() repeat
-
@chiizujin Thanks for that. The second loop does not seem to be necessary to cause the problem.
-
gothon on Discord was talking about something similar this morning:
That is to say, don't do this:
NodeArray[I] = [ .Vertex = {1,2,3}, .Next = 4 ]
because the previous struct at position I will need to be freed by Fuze, and that
may become a memory problem that crashes your program if you do it too many
times.This made me realise that my code (in my actual game) will still eventually crash since I'm still reassigning, just much less frequently. The solution is to do as gothon suggested. In the example above this is:
item = list[i] list[i].a = item.a list[i].b = item.b
This no longer crashes.