简体   繁体   中英

Segmentation fault in recursive function

I recently read about memoization for the first time(I'm a noob) and I wanted to try and make a fibonacci function that uses memoization. This is what I've tried, but anything over 1 just gives me a segmentation fault. Any help is appreciated!

unsigned int fibonacci( unsigned int n )
{
    vector<unsigned int> fibvector;
    if ( n <= 1 )
        return n;
    if ( fibvector.size() >= n )
        return fibvector[n];
    unsigned int add = fibonacci( n-1 ) + fibonacci( n-2 );
    fibvector[n] = add;
    return add;
}
vector<unsigned int> fibvector; 

is a local variable. each time you call fibonacci(n) there will be a new vector created, with no elements. You can fix it by making it static.

static vector<unsigned int> fibvector(MAXELEMENTS); 

MAXELEMENTS is used for initialization purposes. And in this case, you need to test using

if(fibvector[n] != 0) return fibvector[n];

Edit: If you want to not require a fixed amount of elements you can use the following

unsigned int fibonacci( unsigned int n )
{
    static vector<unsigned int> fibvector;
    unsigned int fib;

    if ( fibvector.size() > n )
        return fibvector[n];
    if(n <=1){
       fib = n;
    }
    else{
       unsigned int v2 = fibonacci( n-2 );
       unsigned int v1 = fibonacci( n-1 );
       fib = v2 + v1;
    }
    fibvector.push_back(fib);
    return fib;
}

The idea is that the recursion method of fibonacci(n) would first compute fibonacci(0), fibonacci(1), fibonacci(2) till fibonacci(n). Which means it will compute following the natural order of n, and the push_back will accurately follow this ordering.

Others have commented on your lack of push_backs for your vector. I'll add that your vector is purely local to one call of your function--it has no scope up and down the recursive call stack so it won't function as you anticipated. Instead, you need to make the vector static , or better yet pass it by reference to each recursive call. Better still would be to make this a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM