Search code examples
c++buffer-overflow

The effects of writing past the end of an array


I found some C++ code that does something like this:

struct Test
{
    int a[128];
    char b[768];
};
 
int main()
{
    Test test;
    for( int i = 0; i < 200; ++i)
        test.a[i] = 1;
    return 0;
}

I realize it's wrong. But, I want to know what the effect will be? On GCC 4.3.4, the Test::b array is untouched. Is that guaranteed? What is happening here?

Is it the same effect for reading? e.g.

int main()
{
    Test test;
    for( int i = 0; i < 200; ++i)
        int z = test.a[i];
    return 0;
}

Solution

  • It's undefined behavior, and anything can happen.

    There's much more variables to take into account than just the compiler - version, OS, hardware, weather, what day of the week it is, etc.

    The standard says that undefined behavior can mean anything, so you can't really have any expectations, not even with the same compiler.

    If, for example, you had a different variable located just after test.a, you could get an access violation. Or you could simply overwrite that variable. Anything goes.

    Basically, it's not the writing part that undefined in this case, but the call to

    test.a[i]
    

    with i>=128. It's just not permitted.