I have this code in C++ which is giving weird output:
#include<iostream>
using namespace std;
int main(){
int r[15]={0};
int n = 5;
r[15]=20;
cout<<n;
}
The output should obviously be 5, but it gives me 20. Now I know r[15] is out of bounds. This code should’ve thrown an exception for trying to access r[15], shouldn’t it? However, it compiles normally with g++ and giving wrong output. I’m not able to figure out what’s causing this anomaly. Can anyone help?
Just FYI, this code is just a sample, I had to figure this bug out from a larger code which took me a lot of time which, otherwise, could’ve been saved if an exception was thrown.
Update:
I checked the following code:
#include<iostream>
using namespace std;
int main(){
int n = 5;
int r[15]={0};
r[15]=20;
cout<<n;
}
Output:
20
I checked the following code too:
#include<iostream>
using namespace std;
int main(){
int n = 5;
int a=5;
int r[15]={0};
r[15]=20;
cout<<n<<endl<<a;
}
Output:
5
5
So if the stack explanation is correct, either of the values should’ve been modified in this case too, right? It doesn’t.
Since r is a 15-element array,
r[14]is the last element. Thereforer[15]=20;is undefined behavior. C++ doesn’t do bounds checking so you won’t get exceptions when dealing with plain arrays.In your case
r[15]=20happens to overwrite the stack at the precise location wherenis stored.