Your program is littered with an impressive amount of undefined behavior, for being so small. Undefined behavior means that the behavior of your program is not determinable, as far as the C++ standard is concerned. In other words, anything can happen, as far as the C++ standard is concerned.
int myArray[5];
In this statement, you've left the values of myArray
uninitialized. While this is not undefined behavior by itself, it will be when you try to read those values before you write to them, which you do.
myArray[n] += n++;
This statement, by itself, with no other context, is undefined behavior. It is not specified whether the n
in myArray[n]
is evaluated first, or n++
is evaluated first. In other words, these two expressions are unsequenced with respect to each other. One is reading the value of n
, the other is modifying it. Reading the value of a variable and modifying it without an intervening sequence point is undefined behavior.
Finally, assuming the code above behaves in a manner you expect, you are looping forever, continually incrementing n. Once n reaches 5, you no longer have permission to read or write to those locations in myArray
. Once n reaches 6, you no longer have permission to even refer to those locations. To do so is more undefined behavior.
The first two problems I described, while they are bad, in reality they very likely do not lead to the kind of behavior you are seeing (not by themselves at least). The third one, writing to memory locations beyond the end of your array, that is most likely the culprit in the major errors you are seeing.