-2

I made In C++ a code like this:

int main() {
    int myArray[5];
    int n =1;
#define EVER ;;
    for(EVER){
       myArray[n] +=n++;
    }
    return 0;
}

I let it run and I get a blueScreen. After this my computer dont want to boot. What I did wrong? I'm new with C++. Thanks

Hydroid
  • 119
  • 3
  • 16

2 Answers2

5

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.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • I agree with all of your answer except the part about reading `n`. Isn't the post-increment operator explicitly defined to take effect after the statement is executed? In other words, the value of `n` is 1 in the first iteration, 2 in the second, and so forth. – Vinod Vishwanath Apr 15 '13 at 18:35
  • @VinodVishwanath: Read this: http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – Benjamin Lindley Apr 15 '13 at 18:37
  • Thanks, interesting point. – Vinod Vishwanath Apr 15 '13 at 18:43
1

This version will be work fine. It will fill array but no all computer memory.

int main()
{
  int myArray[5];

  for(int n = 1;;++n)
    myArray[n % 5] = n;
}