Search code examples
assemblyrecursionx86fibonaccignu-assembler

recursion in asm program


I've a question about asm (x86 / GAS) program that returns a segmentation-fault. It's about Fibonacci : I think that the algorith is ok : (pseudo-code)

fibo(int number){
    if (n < 2)
        return number;
    return fib(n - 1) + fib(n - 2);

I don't understand why there is an error. A C program calls the asm function.

Here is the code :

fibo:
    movl    4(%esp), %ebx    #argument n in %ebx
    cmpl    $2, %ebx          # test: is n < 2 ?
    jnl     recur            # no, recursion

    jmp     quit             # yes : quit

recur:


    movl    %ebx, %eax  # get value of argument n
    subl    $1, %eax     # n-1
    pushl   %eax        # push n-1
    call    fibo        # recursive call : fib(n-1)
    movl    %eax, %edx  # save result in  %edx
    movl    %ebx, %eax  # get value of argument n
    subl    $2, %eax     # n-2
    pushl   %eax        # push n-2
    call    fibo        # recursive call : fib(-2)
    addl    %edx, %eax  # add fib(n-1) + fib(n-2)

Can you help me to find where is segfault ?

thanks !

PS: here is the ret :

quit:   movl    %ecx, %eax  #result in %ecx
        ret

Solution

    1. How to you return from your function?
    2. Do you expect your call to preserve the values in registers?

    The answers will get you the solution.