Question

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
Was it helpful?

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.

OTHER TIPS

As others have pointed out, you don't show your ret instruction, which is important. Also, you save the intermediate result of add in edx. That's not going to work - the recursive call that follows is also going to do that and will clobber the value you had at this call level. You'll need to store that intermediate value on stack as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top