Here's the test code:
#include <stdio.h>
struct test
{
int m[1];
};
struct test2: public test
{
int m1[22];
void set(int x, int y) { m[x] = y; }
};
int main()
{
test2 t;
t.m[1] = 123;
t.set(0, 0);
t.set(1, 1);
printf("%d %d\n", t.m[0], t.m[1]);
return 0;
}
I compile it once without and once with optimization:
$ g++ -O0 testf.cpp
$ ./a.out
0 1
$ g++ -O2 testf.cpp
$ ./a.out
1 123
It seems to me that gcc sees array size m[1] and optimizes access to it to be always to the first element m[0]. The question is: is it optimization bug or, some C++ rule is broken so that gcc can do what it does, and if so then what rule?
Note that no memory/stack overrun takes place because of extra m1[22] memory (which was by design in the real app). I don't ask if that's a good programming style, I'm just curious to get the correct answer to the question above.
UPDATE: I accepted the answer with std details, but the biggest help was the comment with the following link: Is the "struct hack" technically undefined behavior?