Subscripts going out of range in an array

后端 未结 1 1203
猫巷女王i
猫巷女王i 2021-01-29 16:45

Here the subscripts of the array are out of range.

 int a[10], i;
for (i = 1; i <= 10; i++)
a[i] = 0;
printf(\"India\");

The output is an i

1条回答
  •  一整个雨季
    2021-01-29 17:22

    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.

    0 讨论(0)
提交回复
热议问题