-1

So i tried below program with its expected output,

int main()
{
    int x = 0;
    int a[5];
    int len = *(&a + 1) - a; //length of array
    cout << "LEN:" << len << endl;

    //len = 20;
    for (int i = 0; i < len; i++) {
        a[i] = i;
    }

    cout << "X  :" << x << endl;
    return 0;
}

Which gives expected output:

LEN:5
X  :0

Then i uncommented line 8 (//len = 20;) and tried again, which again gave the above correct output.

Then i commented line 8 and changed loop to for (int i = 0; i < 20; i++) {, which gives below output,

LEN:5
X  :6

I was expecting x to be 0 since x has nothing to do with the loop (or does it?), then i got this x as 6. Also it threw Segmentation fault which is also expected in line 10 (accessing out of bound). Could anyone please explain what cause for this behavior? It was compiled with gcc in windows environment.

(FYI: this is just an experimenting code)

benjamin c
  • 2,278
  • 15
  • 25

1 Answers1

4

In general, writing beyond the end of an array results in undefined behavior. This can cause unrelated code to change in unexpected ways.

The undefined behavior in your second example can be reduced to:

int main() {
  int a[5];
  for (int i=0; i<20; i++)
    a[i] = i; // undefined behavior once i reaches 5.
}

If you're asking how this particular outcome is possible, if x and a are stored near each other on the stack, than modifying beyond the end of a could inadvertently change the value of x.

Determining what is going on with undefined behavior can become very difficult in larger programs, because the compiler is allowed a lot of freedom in deciding how and where to store variables. (and will potentially store them in multiple places simultaneously)

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173