Pardon the confusing question title, but I was unsure how to phrase it more clearly.
In C, accessing an array out of bounds is classified as undefined behavior. However, array elements are guaranteed to be laid out contiguously in memory, and the array subscript operator is syntactic sugar for pointer arithmetic (e.g x[3] == *(x + 3)
). Therefore, I would personally expect the behavior of the code below to be well-defined:
int array[10][10];
int i = array[0][15]; // i == array[1][5]?
If my interpretation of the standard is correct, this would be undefined behavior. Am I wrong?
According to the standard, it is clearly undefined behaviour as such a case is explicitly listed in the section J.2 undefined behaviour (found in an online C99 standard draft):
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 declarationint a[4][5]
) (6.5.6).
It can still be the case that your example will work, and actually I have seen a lot of such cases in C code; However, to be accurate, it is UB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With