Created attachment 40938 [details] Test code which shows this issue When I compile this code: #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdio.h> typedef enum { e_0, e_1, e_2, e_3, e_4, e_5, e_6, e_7, e_8, e_9 }EEEE; int dummy_array[8]; int main(void) { int x = dummy_array[8]; EEEE e; printf("X = %d\n", x); printf("address of dummy_array[0] = %p\n", &dummy_array[0]); printf("address of dummy_array[100] = %p\n", &dummy_array[100]); for (e = e_0; e<e_9; e++) { printf("TEST: %d\n", dummy_array[e]); } return 0; } using: gcc -O3 -o test test.c then the for loop never exits ( eventually resulting in seg fault ) If I compile un-opitmised or change: EEEE e; to volatile EEEE e; or to int e; or the array to: int dummy_array[10]; then the loop exits as expected. I know that the array access in the original code is out of bounds and such an access is undefined but we'd expect the for loop to exit even in this circumstance. I tried MSVC and it behaves in an intuitive manner. I've attached a tgz file of my test build with: gcc -v -save-temps -O3 -o test test.c Thanks
Given the UB you're invoking, all bets are off and the compiler is free to do anything. I don't think we want to change anything here. Even -Warray-bounds warns here.
Thanks for your quick reply. However, this is not intuitive, the compiler should be "free to do anything" in a sensible intuitive manner. The for loop is well defined and there is no conceivable circumstance that should allow it to loop forever. The optimized/unoptimized code should work the same but it does not. If you want to make the unoptimized code loop for ever I'll be more than happy Thanks again.
No, undefined behavior means undefined behavior, anything can happen once you trigger it, it can format your disk, launch missiles, do nothing, do what you expect, do somethng different. The compiler optimizes on the assumption that the code is valid and does not invoke undefined behavior.
Please read e.g. http://blog.regehr.org/archives/213 or other articles about UB and just fix your code.
Thanks for your feedback.