Why i am not getting error array index out of bound in c++?

help
array

#1

why this piece of code is working fine without indexoutofbound exception?

for(i=0;i<n;i++)
{

if((a*+1)==a[i+1])//which area and value i am accessing by a[i+1] when i==n-1?

    {

k++;

}

}

but this will give arrayindexoutofbound exception in java.Please help me.


#2

That’s because bound checking is undefined behavior in C/C++. https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why

Also, search online and read more about unspecified and implementation defined behavior.


#3

In C/C++, array bound checking is not there because if you have a memory pointer it doesn’t stop you from accessing it, as long as you don’t try to access which you are not supposed to, in which case it will through segmentation fault.

As this is error prone, JAVA handles such scenario by not letting you access such locations by throwing an exception.


#4

https://www.codechef.com/viewsolution/13794504 i got ac,any reason? means which area of memory i am accessing?what is value of a[n] in this case? garbage?


#5

Could be anything in memory… probably one of your variables, of just any empty register. Sometimes it works, sometimes you get WA. It´s different depending of the code.