Hi!
I'm not sure if this is a bug or not, so I'm hoping someone here can help me
find out.
I've been using -O2 to compile a mathematical simulation program, and it has
worked fine until now. I recently upgraded g++ from 4.5.3 to 4.6.1 in Debian Sid
(on Amd64 architecture).
Now I get incorrect numerical results. I've narrowed the problem down to the
-fstrict-aliasing that is included in the -O2 option.
My program uses the Blitz++ v0.9 array library. I've simplified and simplified
in order to obtain a minimal example code, which I have included below. Not sure
how to make it any simpler without the problem going away... I even reduced the
outer for-loop to do only a single iteration, and the blitz arrays to have only
one component.
Here is the program code:
--------------------------
#include "iostream"
#include "blitz/array.h"
int main()
{
blitz::Array<double,1> X(3); X = 0.0;
blitz::Array<double,1> var(1); var = 0.0;
for(int i = 0; i != 1; ++i) {
for(int c = 0; c != 3; ++c) X(c) = double(c);
var(i) = 0.0;
for(int c = 0; c != 3; ++c) var(i) += X(c)*X(c);
var(i) /= 3.0;
}
std::cout << var(0) << std::endl;
return(0);
}
---------------------------
If I compile with "-O2", it prints 0, which is wrong.
If I compile with "-O2 -fno-strict-aliasing", it prints the correct answer 1.6666..
I've verified that the problems goes away after downgrading to g++-4.5.3.
Am I doing something wrong in the code above? I think I had similar problems
before with g++-4.1.3, and I had to use "-O2 -fno-strict-aliasing" back then.
I know it is a hassle to try my example code, since it uses blitz... Sorry about
that. The problem seems to disappear if I replace the one-component blitz array
with a scalar double.
Interestingly, the problem also disappears if I remove either of the lines
var(i) = 0.0;
var(i) /= 3.0;
Best regards and thanks,
Torquil Sørensen