When investigating a problem, I stumbled upon code, which boils down to the following example:
const unsigned long long int MAX=9223372036854775807ULL; //2^63-1
void double_it(double *d){
for(unsigned long long int i=0;i<MAX; i++){
d[i]=2*d[i];
}
}
Due to some mistakes, the for loop runs much further than there is memory and the program crashes. But this is not the interesting part.
When compiled with gcc (gcc -O2 -Wall -std=c99 -c
), this code leads to the following warning:
warning: iteration 2305843009213693951ull invokes undefined behavior [-Waggressive-loop-optimizations]
which cause I don't understand.
There are some similar questions on stackoverflow, e.g.:
- g++ "warning: iteration ... invokes undefined behavior" for Seemingly Unrelated Variable
- Why does this loop produce "warning: iteration 3u invokes undefined behavior" and output more than 4 lines?
But those problems were integer overflows, here the counter i
is seemingly nowhere near an overflow.
Compiling the same code without -O2
does not lead to such a warning, so I guess -Waggressive-loop-optimizations
is an important part.
So actually, I have two questions:
- What is the problem with this code (compiled for Linux x86-64)?
- Why there is no warning without
-O2
? If this code is faulty, I would expect it to be faulty no matter whether it is optimized or not.
The behavior is the same for g++ (see it online at coliru).