Thanks very much indeed -dev and all for your help; I don't know how long it would have taken me to figure out flushing the buffer was the solution
It wasn't the solution. Fixing the array index problem was. Flushing the buffer simply made debugging more effective.
Of course, defensive coding would not have allowed the problem to occur in the first place.
EVERY place where I write to an array, I make sure that the index is in range. You should get into that habit, too, especially as you have now been burned by not doing that.