C++ weird array behaviour

Viewed 312

I was debugging my code for key index counting and found this problem. I do not understand what is happening here. I've looked at the code for too long to see if I am missing something very obvious, but it does not seem like it.

 int main()
{
    const int r=7,len=10;
    int arr[10]={1,4,6,2,0,4,3,6,5,2};
    int count[r+1]={0};
    for(int i=0;i<len;i++)
    {
        count[arr[i]+1]++;
    }
    cout<<arr[0]<<" ";

    for(int i=0;i<r+1;i++)
    {
        count[i+1]+=count[i];
    }
    cout<<arr[0]<<" ";
    return 0;
}

This is the kind of a mock up code which generates the same bug.

Output:-

1 11

I am not changing value of arr anywhere in my program and still it shows 11 instead of 1 in the output.

if I comment out count[arr[i]+1]++; or count[i+1]+=count[i]; or both it gives the correct output.

1 1

What is happening please explain. (comment if I am doing something silly).

Edit: This is only happening with arr[0].

1 Answers

Compiling it with g++ -Wall -Wextra you get this warning:

rando_so.cpp: In function 'int main()':
rando_so.cpp:15:19: warning: iteration 7 invokes undefined behavior [-Waggressive-loop-optimizations]
         count[i+1]+=count[i];
         ~~~~~~~~~~^~~~~~~~~~
rando_so.cpp:13:18: note: within this loop
     for(int i=0;i<r+1;i++)

This hints you to look a bit closer at that second loop. Your variable i goes up to the highest possible index of count - and then you add 1. That is undefined behaviour. In your case, it is likely that you happen to be writing into the first element of arr now, because of how it's laid out on the stack. But as far as I know, anything could happen as a result of this.

Related