The compiler goes in segmentation fault with a fibonacci facuntion call (greater that 1)

my code is:

function fib(n::Integer)
    if n <= 1
        return n
    end
    
    return fib(n - 1) + fib(n + 2)
end

for i = 0:40
    println(fib(i))
end

and the output is:

0
1
[2]    5540 segmentation fault (core dumped)  julia fib.jl

why this?
it’s a fault of my code or of the compiler?
am I doing something wrong?

You probably meant fib(n - 2) (not n+2). You wrote an infinite loop.

1 Like

This should be fib(n - 2), not fib(n + 2).

This bug in your code causes infinite recursion, which should lead to a StackOverFlowError, not a core dump. That’s what I get on my machine:

julia> for i = 0:40
           println(fib(i))
       end
0
1
ERROR: StackOverflowError:
Stacktrace:
 [1] fib(::Int64) at ./REPL[1]:6 (repeats 79984 times)

What version of Julia are you using?

1 Like

oof, you’re right

1 Like