c++loopsoutputlong-long

Unexpected long long value in C++


In my code I simply scan values of t, n and m respectively. While debugging I found that whatever value I give to m, it is taking the value 0. You can run this code for input :

1
3 4

Here, the output should be 4, but unexpectedly its 0. On the other hand, when I scan the values of n and m after the for loop, the output comes as expected (i.e. 4 in this case). I have commented out that line so that you people can figure out why this is happenning.

#include <bits/stdc++.h>

using namespace std;

int main()
{
    long long t,n,m,i,j;
    scanf("%lld",&t);           // Scan t (of no use)
    while(t--){

        scanf("%lld %lld",&n,&m);       // If I scan n and m here, the 
                                       //output is always 0
        long long x[9000],y[9000],ans[9000],in=0;
        for(i=1;i<=9000;i++){
        ans[i]=0;
        x[i]=0;
        y[i]=0;
        }
    //scanf("%lld %lld",&n,&m);//Output is correct if I scan the values here
        cout<< m << endl;
    }

}

Solution

  • When i = 9000, you will end up accessing an out-of-bounds memory in the following statements. This leads to undefined behaviour.

    ans[i]=0;
    x[i]=0;
    y[i]=0;