Why is the online compiler of codechef giving different output for the same input everytime I run?

I was trying this problem:-
Practice Coding Problem - CodeChef

Solution: 1055841538 (codechef.com)

If you cheak my solution you will findout that , for input:-
1
3
4 6 10

the output is somehow different everytime…
For my local machine its working fine…
But in online compiler of codechef…it generates different output everytime.
Sometimes it manages to give the correct ans and other time it gives wrong ans…
How is this possible that, same code is giving different output everytime?
Can someone help?

Because you are making an extremely unsafe coding here:

        int arr[n+1];
        for(int j=1;j<=n;j++)
        {
            cin>>arr[j];
        }
        long long int prefix[n+1]{0};
        prefix[0]=arr[0];

        for(int j=1;j<=n;j++)
        {
            prefix[j]=prefix[j-1]+arr[j];
        }

You create an array of integers.

You never fill array[0]

You pass that never filled array[0] to prefix[0]

You add God knows what is in array[0] to your array of prefixes.

It makes an undefined behaviour because C/++ array/vector memory allocation (both dynamic and static) only takes free system memory, and that may have data from previous use of that part of your hardware.

If it “works” in your computer, it’s maybe because your compiler or your OS set the memory with ‘0’ before sent to your program, but that’s not a canonical behaviour, and it shouldn’t be assumed.

If you want a clean (with 0) array or a vector, you must clean it yourself.

For arrays (memset not best practice because it works on byte length):

int size = 50;        // Any number
int array[size];
memset(array,0, sizeof(array));

For arrays with loops

int size = 50;        // Any number
int array[size];
for(int i=0; i<size; i++){
    array[i] = 0;
}

For vectors:

int size = 50;
vector<int> array (size,0);

However, when you create an unordered_map entry like this:

unordered_map<int,int> dic;
dic[15];
cout << dic[15] << endl;

Output will be ‘0’

Why it sets 0 here, but not in vectors? I don’t know lol
These are the misteries of C/C++ :joy: