2

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].

6
  • 3
    Typical buffer overflow issue. Use a debugger to step through the code, statement by statement while monitoring the values of all variables. It helps if you break up complex expression into simpler expressions (like count[arr[i]+1]++; could be broken into int temp = arr[i]; count[temp + 1]++;). Commented Jan 2, 2021 at 10:54
  • As a hint, think about what possible values i can be in the second loop. And what index i + 1 then would be. Commented Jan 2, 2021 at 10:56
  • @Poseidon I believe this compiler warning pretty well explains what's going on. Futile to investigate why code which has undefined behavior, behaves like it does. Commented Jan 2, 2021 at 10:59
  • @Someprogrammerdude Oh, Thank you I knew I was doing something silly!!!! Commented Jan 2, 2021 at 11:00
  • Also, should I delete the question now? I am new to this!!! Commented Jan 2, 2021 at 11:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it. Thank you. the 'anyhting can happen' part is the scariest thing as it might not have affected the program at all(at least that is what i understand) and I would've proceeded with my day.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.