I’m trying to solve a homework assignment – I managed to produce a working piece of code but it’s producing the wrong answer. I tried debugging with gdb but I still can’t see what’s wrong with my code.
.data
a : .long 6
r : .long 0
out : .string "result %d\n"
.text
.global main
fib:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %eax
cmpl $0, %eax #fib(0)=0
je endf
cmpl $1, %eax #fib(1)=1
je endf
decl %eax #eax=n-1
movl %eax, %edx #edx=n-1
pushl %edx #save n-1
pushl %eax #set arg
call fib #re in ecx
popl %eax #get n-1
decl %eax #eax=n-2
pushl %ecx #save result for n-1
pushl %eax #set arg
call fib #res in ecx
popl %eax # eax=fib(n-1)
addl %eax, %ecx #fib(n)=fib(n-1)+fib(n+2)
movl %ebp,%esp #Exit
popl %ebp
ret
endf:
movl %eax, %ecx#fib(0) or fib(1) to %ebx
movl %ebp,%esp
popl %ebp
ret
main:
pushl a #stack [a]
call fib #result in %ecx
pushl %ecx
pushl $out
call printf
Note that you are not removing any arguments you pass to
fibanywhere, so your stack becomes unbalanced. See the fixed version in operation.Also, typical calling conventions return values in
eax. Usingecxfor no good reason is confusing. See a simplified version that adheres to conventions better.