0

我编写了应该计算以下递归函数的汇编程序:

f(n) = f(n-1) + 2*f(n-2) - f(n-3)

对于 n = 0 和 n = 1,它返回 1,对于 n = 2,它应该返回 0。但是对于这个值程序总是返回 0,看起来下面的条件从未满足。

if0:              
  mov eax,1
  jmp end
if1:               
  mov eax,1
  jmp end          
if2:               
  mov eax,0
  jmp end 

对于任何其他值(大于 2),我都会收到分段错误。下面是整个代码:

.intel_syntax noprefix
.globl main
.text

main:

  mov eax, 3

  push eax
  call f

  push eax
  push offset msg
  call printf
  add esp, 8

  mov eax, 0
  ret

f:
  push    ebp        
  mov     ebp,esp   
  add     ebp,12     
  mov     ebx,[ebp]   

  cmp     ebx, 0      
  jz     if0
  cmp     ebx, 1
  jz     if1
  cmp     ebx, 2
  jz     if2

  lea ecx, [ebx-1]
  push ecx            
  call  f             
  pop ecx            

  push eax            
  lea ecx,[2*ebx-2]
  push ecx           
  call  f            
  pop ecx             
  pop eax         
  add eax,ecx        

  push eax
  lea ecx, [ebx-3]
  push ecx            
  call f             
  pop ecx             
  pop eax             
  sub eax,ecx
  jmp end

if0:              
  mov eax,1
  jmp end
if1:               
  mov eax,1
  jmp end          
if2:               
  mov eax,0
  jmp end         

end:
  pop     ebx         
  pop     ebp         
  ret

msg:    .asciz "Output = %d\n"

我不知道我做错了什么。编辑:所以,我已经对 ebp 进行了试验,并将 add ebp,8 更改为:add ebp, 16。而且,现在它适用于基本条件。在我看来,堆栈溢出存在问题,但我看不到它在哪里。

4

1 回答 1

2

pop ebx没有相应push的,弄乱你的堆栈。很可能还有其他错误,但那是我跳出来的错误。

于 2016-12-13T18:34:01.750 回答