A friend of mine (we work together) wrote the following C++ code:
And his app crashed in the release build (debug build worked OK).
The prototype of F(x) is following:
This F function is inline. It only calls 3-4 another inline functions.
The app crashed because of 2 reasons:
My friend fixed the bug in 1 minute:
After that I had a 20-minutes argumentation with my friend.
I told him he was wrong returning the value by reference. Or at least in this case.
He told me the compiler was wrong screwing up the operators precedence.
result += a*F(i) + c*F(j);
And his app crashed in the release build (debug build worked OK).
The prototype of F(x) is following:
template<class T> inline T& ContainerClass<T>::F(size_t i);
This F function is inline. It only calls 3-4 another inline functions.
The app crashed because of 2 reasons:
- The compiler (namely, Visual Studio 2005 building 64bit Windows executable) thought there's a plenty of space for optimisation. That's why the compiled code calculates F(i) and F(j) almost in parallel (SSE instructions, XMM registers, etc.). Then it calculates a*F(i) and c*F(j) (it does it simultaneously, too), then it finally calculates the resulting variable.
- The F function returns a reference to some element (in this case, a reference to float). The actual value was stored in some kind of container owned by ContainerClass. Because F(j) in that code calculated prior to the a*F(i), that reference screwed up.
My friend fixed the bug in 1 minute:
float add1 = a*F(i); float add2 = c*F(j); result += add1 + add2;
After that I had a 20-minutes argumentation with my friend.
I told him he was wrong returning the value by reference. Or at least in this case.
He told me the compiler was wrong screwing up the operators precedence.
Who was right?
Me
5(71.4%)
My friend
1(14.3%)
Both
0(0.0%)
Neither (plz explain)
1(14.3%)
