Is it undefined behavior to access an array out of bounds if I know what data is at the accessed adress?

Imagine the following definition.

struct X {
    double a[8] {0.0};
    double b[8] {0.0};
}

int main() {
    X x;
    x.a[10] = 1.0;
}

Is the behavior of the program undefined when I access x.a[10]?

>Solution :

Yes, it is undefined behavior, but not only because the compiler may alter the memory layout of X.

It is undefined behavior because the standard says so. As a result the compiler can do whatever with this code: the compiler can drop the assignment completely, can assign 1.0 to all the 16 elements, can change what previous code is doing, can crash the program, format your hard drive, etc.


A more realistic, classical example: the following function

const int table[4] = {2, 4, 6, 8};

bool exists_in_table(int v)
{
    for (int i = 0; i <= 4; i++) {
        if (table[i] == v) return true;
    }
    return false;
}

always return true, at least in modern gcc with -O3 (https://godbolt.org/z/f9cbWMYzM)

Leave a Reply