Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading