0

so I wrote this code:

#include <iostream>

constexpr
int fibonacci (int n) {
    int a = 0;
    int b = 1;

    for(auto i = 0; i < n; i++) {
        b += a;
        a = b - a;
    }
    return b;
}

template<int N, int (T)(int)>
struct array {
    using type = decltype(T(0));

    constexpr array() : arr() {
        for (auto i = 0; i < N; ++i) {
            arr[i] = T(i);
        }
    }
    const type &operator[](int i) const { return arr[i]; }

private:
    type arr[N];
};

int main() {
    constexpr auto x = array<10, fibonacci>();

    for (int i = 0; i < 11; i++) {
        std::cout << i << " " << x[i] << std::endl;
    }
}

And without optimizations it works as expected, prints 11 values with last one being random value. But as soon I move to -O2 I get randomly long list of numbers finished with crash and segmentation fault. I checked this result on godbolt.org (https://godbolt.org/z/4MqjbPbxE) and it seems that it is not a problem in, for example, clang.

My question is, is this a bug in gcc? Why would optimizations remove/not check condition in for loop?

4
  • 6
    Indexing out of bounds is UB. Getting different results at different optimization levels is a perfectly reasonable result of UB.
    – cigien
    Apr 9, 2021 at 18:10
  • I was very confused by array<10, fibonacci>. I thought it was meant to be std::array. Apr 9, 2021 at 18:17
  • 1
    If i >= 10 then you have Undefined Behavior. The compiler is allowed to notice this, and assume that i < 10 is always true. And with that assumption, i < 11 is simply true. Apr 9, 2021 at 18:20
  • 1
    And why would it make that assumption? Speed. One less thing it needs to test. The less the program has to do, the faster it is. Your code is not a list of instructions to be performed by the computer. It is a description of behaviour. The compiler's job is to take that behaviour and produce the list of instructions. The higher the optimization level, the more time the compiler will will spend finding faster ways to produce the described behaviour, and it will do anything it wants to your code to get fast without changing the behaviour. If you describe the behaviour even a little bit wrong... Apr 9, 2021 at 18:41

2 Answers 2

2

You are invoking undefined behavior by using out-of-range x[i].

Allocate one more to avoid out-of-range access.

In other words,

    constexpr auto x = array<10, fibonacci>();

should be

    constexpr auto x = array<11, fibonacci>();

Defining constant to avoid typo is better:

int main() {
    constexpr int num = 11;
    constexpr auto x = array<num, fibonacci>();

    for (int i = 0; i < num; i++) {
        std::cout << i << " " << x[i] << std::endl;
    }
}
0
0

Fix checking index.

for (int i = 0; i < 10; i++) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.