2012-11-18 55 views
2

我試圖解決作業分配 - 我設法生成了一段代碼,但它產生了錯誤的答案。我試着用gdb進行調試,但是我仍然看不到我的代碼有什麼問題。遞歸斐波那契IA32程序集

.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 
+1

去得到你的功課,在這裏解決:http://stackoverflow.com/questions/5616684/recursive-fibonacci-in-assembly?rq=1 – kcsoft

+1

我看到了,但我真的需要了解我在做什麼錯 – ketrox

+0

你從gdb的調試嘗試中學到了什麼? –

回答

1

注意,你是不是刪除你傳遞給fib任何地方任何參數,因此你的籌碼變得不平衡。請參閱the fixed version in operation

另外,典型的調用約定返回值爲eax。使用ecx沒有很好的理由是令人困惑的。查看更符合慣例的simplified version