[Solved] Subscripts going out of range in an array


The idea that this will form an infinite loop is based on an assumption about how the variables will be laid out in memory. In particular, it assumes that because i is defined immediately after a, that it will also be allocated in memory immediately after a.

That’s certainly not guaranteed, but it equally certainly could happen. If it does, then the write to a[10] may actually overwrite i. Since it’s writing 0 into the nonexistent a[10], doing so actually writes 0 into i. Then when the condition in the loop checks that i <= 10, that’s true, so the loop continues — and each time i gets to 10, it’s immediately overwritten with 0 before the loop condition is evaluated, so the loop re-starts from the beginning.

As far as either the C or C++ standard cares, it’s just undefined behavior–when the code writes past the end of the array anything can happen. It might do what somebody expects, or might might do something entirely different and unrelated that doesn’t seem to make sense at all. The compiler is free to emit code that does pretty much anything in such a circumstance (or it could, for example, diagnose it as an error, and emit no code at all).

To give some idea of what conforming behavior could be: early versions of gcc had code to detect a specific case of implementation-defined behavior (pretty much like undefined behavior, except the implementation has to document what it does). In this case, the documented behavior was fairly complex. The compiler would attempt to do each of the following in order (and stop at the first one that succeeded):

  1. run nethack (a game)
  2. run rogue (another game)
  3. start emacs, and have it execute a towers of hanoi simulation
  4. print out “You are in a maze of twisty little passages, all alike”.

I could be getting the order of those a bit wrong (this was a long time ago), but you get the idea. The result had nothing to do with anything a reasonable person would be likely to expect.

1

solved Subscripts going out of range in an array