【问题标题】:Counting recrusive function in IA86 assembly - unexpected values计算 IA86 程序集中的递归函数 - 意外值
【发布时间】:2016-12-13 17:59:53
【问题描述】:

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

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 并且我已经改变了 添加 ebp,8 到: 添加ebp,16。 而且,现在它适用于基本条件。在我看来,堆栈溢出有问题,但我没有看到它在哪里。

【问题讨论】:

  • 你希望处理器在执行if0: mov eax,1后做什么?
  • 当ebx等于0或1时,将1移到eax,eax是存放结果的寄存器。
  • 再次阅读我的问题。 做什么 做什么 期望处理器做一次它已经执行if0: mov eax,1?
  • 对不起,我没听清我看到我的错我想停止执行程序。我看到我应该在这里添加jmp end
  • 现在您更改了问题中的代码,它仍然失败吗?

标签: recursion assembly x86 intel-syntax


【解决方案1】:

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

【讨论】:

  • 不幸的是,这根本不能解决问题,即使看起来你是对的。
猜你喜欢
  • 2015-07-28
  • 1970-01-01
  • 2019-06-13
  • 2020-01-29
  • 2015-03-29
  • 2012-12-11
  • 2022-11-25
  • 1970-01-01
  • 2016-08-08
相关资源
最近更新 更多