At first glance i'd say that your problem is that "myArray" is not initialized, so that it can have a random initial length when you don't add "setLength(myArray,0);" at the beginning.
This is indeed the principal problem.
FPC sets the length of most dynamic arrays (including strings) on initialization to zero reliably.
However, for dynamic arrays of
Integer and
Byte (and possibly other types) the array Length() after (compiler) initialization is non-zero. In my testing it is not random, but this may just be an artefact of my system, and anyway is undocumented and presumably implementation-dependent.
The bottom line is that all dynamic arrays, and particularly arrays of Byte or arrays of Integer should be initialised by the programmer either by assigning Nil to the array or using an explicit SetLength(xxx, 0).