Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is accessing an element of a multidimensional array out of bounds undefined behavior?

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?

like image 398
hiy Avatar asked Jun 07 '20 18:06

hiy


1 Answers

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 declaration int 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.

like image 67
Stephan Lechner Avatar answered Nov 13 '22 13:11

Stephan Lechner