Access array beyond the limit in C and C++

Accessing outside the array bounds is undefined behavior, from the c99 draft standard section Annex J.2 J.2 Undefined behavior includes the follow point:

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

and the draft C++ standard in section 5.7 Additive operators paragraph 5 says:

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. [...] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

For completeness sake, section 5.2.1 Subscripting paragraph 1 says:

[...]The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note ]

It is important to note that the compiler is not required to produce a warning(diagnostic) for undefined behavior, the draft C++ standard in section 1.4 Implementation compliance paragraph 1 says:

The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard except for those rules containing an explicit notation that “no diagnostic is required” or which are described as resulting in “undefined behavior.”


Yes, it is undefined behavior.

A compiler may or may not warn you against undefined behavior even if it is able to detect it.


This is considered undefined behavior. Compilers aren't required to issue warnings if you try to compile code that will result in undefined behavior, though it's nice of them to do so.