-6

Below is the program where I have created a array of integers that is statically sized to hold five elements. I assigned a value 4 to index 7 of the same array, which is out-of-bounds. Neither the compiler nor runtime show any errors, instead giving me the answer 4.

#include<iostream>

int main()
{
    int ptr[5]={2,4,5,6,7};
    ptr[7]=4;
    std::cout<<ptr[7];
    return 0;
}

I am using g++ version 4.7.2

Nathan
  • 4,777
  • 1
  • 28
  • 35
Venkatesan
  • 422
  • 3
  • 6
  • 19
  • 3
    The compiler is allowed to assume you don't do that. If something goes wrong, it's your own fault. If not, you got (un)lucky. – chris Aug 08 '14 at 13:39

2 Answers2

3

That is because what you are doing is undefined behavior.

It might break or it might not. You cannot rely on anything happening or not happening when you access the array out of bounds since that behavior is not defined by the language or the compiler.

OlivierLi
  • 2,798
  • 1
  • 23
  • 30
2

The behaviour is undefined. The C++ standard mandates that runtime checks on array bounds are not compulsory. This is to prevent degradation of performance.

Certain compilers do issue such errors, particularly in a debug build configuration.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483