user3460211
user3460211

Reputation: 11

Stack corruption around variable `f` trying to calculate fibonacci(n)

I'm trying to get my program to print the n-th fibonacci-number.
I get a stack-corruption-assertion though:

int f[] = { 1, 1 };
int i = 0;
if (n <= 2) {
    cout << "F(" << n << ") = 1" << endl;
    return 0;
}
if (n>2) {
    i = 2;
    while (i < n) {
        cout << "i =" << i << endl;
        cout << f[i - 1] << endl;
        cout << f[i - 2] << endl;
        f[i] = f[i - 1] + f[i - 2];
        i++;
    }
    cout << "F(" << n << ") = " << f[i-1] << endl;
    return 0;
}

Upvotes: 0

Views: 44

Answers (2)

Deduplicator
Deduplicator

Reputation: 45664

Raw arrays do not grow on-demand, the initializer is used to size them statically when the sie is not included in the type.
These two are equivalent, both defining an array of two elements:

int f[] = { 1, 1 };
int f[2] = { 1, 1 };

What you want to use is a std::vector or manual dynamic re-allocation (using either malloc, realloc and free or new[], delete[] and std::copy).

Another (preferable) option is observing the fact that you only need the previous 2 values to calculate the next one, and only save those.

Upvotes: 2

Baum mit Augen
Baum mit Augen

Reputation: 50063

int f[] = {1, 1};

creates an array with room for exactly two integers. You thus cannot write to or read from (or even form) f[i] for i > 1. While you could use an std::vector to safe all values of the recursion, it would be more efficient to calculate the series like this:

int f[3] = {1, 1, 0};
for (int i = 1; i < n; ++i){
    f[2] = f[0] + f[1];
    f[0] = f[1];
    f[1] = f[2];
}

reusing the space of no longer needed values.

Upvotes: 0

Related Questions