views:

1409

answers:

5

I'm having a hard time understanding why

#include <iostream>

using namespace std;

int fib(int x) {
    if (x == 1) {
        return 1;
    } else {
        return fib(x-1)+fib(x-2);
    }
}

int main() {
    cout << fib(5) << endl;
}

results in a segmentation fault. Once x gets down to 1 shouldn't it eventually return?

+54  A: 

When x==2 you call fib(1) and fib(0):

return fib(2-1)+fib(2-2);

Consider what will happen when fib(0) is evaluated...

Georg Fritzsche
+1 for not giving the answer directly but indicating where the problem is. Much better for someone who is learning.
Xetius
+1, I use the same technique with my oldest kid (9) and it stimulates his ability to solve problems.
Gamecat
+12  A: 

The reason is because Fibonacci sequence starts with two known entities, 0 and 1. Your code only checks for one of them (being one).

Change your code to

int fib(int x) {
    if (x == 0)
        return 0;

    if (x == 1)
        return 1;

    return fib(x-1)+fib(x-2);
}

To include both 0 and 1.

LiraNuna
Does not the series starts from 1,1?
Aviator
That's not what I've been taught, and not what Wikipedia suggests - http://en.wikipedia.org/wiki/Fibonacci_number
LiraNuna
@Aviator: Depends on how you define Fibonacci numbers. ;)
Spoike
@Spoike, @LiraNuna: Thanks :) Got it now. Have seen some implementations starting with 1,1,2 etc.,. So got confused!
Aviator
+2  A: 

Why not use iterative algorithm?

int fib(int n)
{
    int a = 1, b = 1;
    for (int i = 3; i <= n; i++) {
        int c = a + b;
        a = b;
        b = c;
    }           
    return b;
}
Dzmitry Huba
That’s the best approach. But he asked for a recursive solution.
Gumbo
@Gumbo, the 'best' approach would be meta-programming, no doubt.
LiraNuna
@LiraNuna: That’s not meta-programming.
Gumbo
I never said it is, I know what meta-programming is, and it involves no runtime calculations *at all*.
LiraNuna
@LiraNuna: Care to answer with a meta-programming example?
Spoike
I don't want to confuse the author, since he is clearly focusing on recursion. If you want to know more, visit http://en.wikipedia.org/wiki/Template_metaprogramming
LiraNuna
A metaprogramming approach would basically boil down to a recursive solution...the calculation would simply be transfered from runtime to compile-time. Claiming that this would be a better approach is non-sense because we don't know the OP requirements: if he just needs to run the program once, having a huge compile time and a short runtime is not better than having a short compile time and a long runtime. Similarly, if he needs to take as input the 'n' parameter, metaprogramming is not usable (except if you explicitely put an upper bound to this number). Moreover, compilers have a limited...
Luc Touraille
...recursion depth, so this can be an issue. To sum up, metaprogramming is a really powerful tool, but should be wisely used, only when it truly fits the problem.
Luc Touraille
+1  A: 

So I was checking out this meta-programming thing that LiraNuna was talking about in the comments of this answer. Taking in the syntax examples, the Fibonnaci can be calculated in compile time with the following:

template <int N>
struct Fibonnaci 
{
    enum { value = Fibonnaci<N - 1>::value + Fibonnaci<N - 2>::value };
};

template <>
struct Fibonnaci<1> 
{
    enum { value = 1 };
};

template <>
struct Fibonnaci<0> 
{
    enum { value = 0 };
};

// Fibonnaci<4>::value == 0+1+1+2 = 3
// Fibonnaci<0>::value == 0

Haven't checked if this compiles and works though.

Spoike
The OP never asked for another solution to the fibonacci generation problem, he just asked for some help to debug his code.
Luc Touraille
@Luc Touraille: Since when has SO stopped other users from derailing into other solutions? ;)
Spoike
It does work. I checked with gcc :-), but only for lower numbers, fails to compile with values over 47 (or so) and overflows at much smaller values. Still very cool though.
Chris Huang-Leaver
@Chris Huang-Leaver: Sweet!
Spoike
A: 

"The OP never asked for another solution to the fibonacci generation problem, he just asked for some help to debug his code".

Personally I should also like a better algorithm.

See exercise 7.11 and 9.4 : http://www.oopschool.com/books/CPB2010.pdf

Best regards Kjell Bleivik

Kjell Bleivik