I currently have the following code for recursively calculating the nth term of the fibonacci sequence in assembly, however it is not working appropriately (only works for the first 3 terms). Could anyone provide any insight?
pushl %ebp
movl %esp,%ebp
movl 8(%ebp),%eax #retrieve argument passed to function in eax
cmpl $1,%eax #identify if its base case
jle fin
decl %eax
pushl %eax #push n-1 to stack for next function call
call _fibonacci
movl %eax,%ecx #store fib(n-1) in ecx
movl 8(%ebp),%eax
subl $2,%eax
pushl %eax #push n-2 to stack for next function call
call _fibonacci
addl %ecx,%eax #add fib(n-2)+fib(n-1)
fin: #end label
movl %ebp,%esp
popl %ebp
ret
call _fibonacci
addl %ecx,%eax #add fib(n-2)+fib(n-1)
Your _fibonacci
function uses %ecx
without saving it (in the non-base case), so the recursive call overwrites the value in %ecx
.
You should save the returned value from the first call to _fibonacci
on the stack instead of in a register.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.