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

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

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

if((a[i]+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.

That’s because bound checking is undefined behavior in C/C++. c++ - Accessing an array out of bounds gives no error, why? - Stack Overflow

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

1 Like

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.

1 Like

CodeChef: Practical coding for everyone i got ac,any reason? means which area of memory i am accessing?what is value of a[n] in this case? garbage?

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.

1 Like