A colleague of mine found this interesting/surprising bug.
It affects clang++ version 6, 7 and 8 when compiling with optimization flag (typically -O2)
The code is really simple, it must compute a finite difference:
a[i] = x[i+1]-x[i]
b[i] = (y[i+1]-y[i])/a[i]
The associate code demo is as follows:
#include <iostream>
#include <vector>
class Foo {
private:
std::vector<double> _a;
std::vector<double> _d;
public:
Foo(const std::vector<double> &x, const std::vector<double> &y)
: _a(x.size()), _d(x.size()) {
for (unsigned int i = 0; i < x.size() - 1; i++) {
_a[i] = x[i + 1] - x[i];
_d[i] = (y[i + 1] - y[i]) / _a[i];
}
}
const std::vector<double> &a() const noexcept { return _a; }
};
int main() {
// Read input file
std::vector<double> x, y;
while (std::cin) {
double xi, yi;
if (std::cin >> xi >> yi) {
x.push_back(xi);
y.push_back(yi);
}
}
// Create Foo instance
Foo foo(x, y);
// Print computed data
for (auto a : foo.a()) std::cout << a << '\n';
return 0;
}
When you use unoptimized clang compilation:
$> clang++-6.0 -std=c++11 -o bug bug.cpp
$> paste <(seq 1 5) <(seq 1 5) | ./bug
you get the expected result:
1
1
1
1
0
however when optimizing (the -O2 option):
$> clang++-6.0 -std=c++11 -O2 -o bug bug.cpp
$> paste <(seq 1 5) <(seq 1 5) | ./bug
you get a wrong result:
1
2
2
0
0
The bug has been confirmed (with a "release blocker" priority) and is now fixed since 2 days: see details here
Please note:
I thought that this bug deserved a mention because it is likely to seriously, but silently, affect a numerical computation code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With