简体   繁体   English

如何在 MASM 程序集中使用堆栈 function 进行递归调用

[英]How to do a recursive call with a stack function in MASM assembly

I am working on a program to calculate the first seven values of a Fibonacci number sequence.我正在开发一个程序来计算斐波那契数列的前七个值。 I was given some C to base it off, yet I am not sure what I have is doing everything quite right.我得到了一些 C 作为基础,但我不确定我所拥有的一切是否正确。 This is only the second time I have done a program in MASM with a stack and I'm not sure on what I did was correct.这只是我第二次在 MASM 中使用堆栈执行程序,我不确定我所做的是否正确。 This is what I was given in C:这是我在 C 中得到的:

//Fibonacci Series using Recursion
#include<stdio.h>
int fib(int n)
{
   if (n <= 1)
      return n;
   return fib(n-1) + fib(n-2);
}
 
int main ()
{
  int n = 9;
  int result = fib(n);
  return 0;
}

And this is what I have in MASM.这就是我在 MASM 中所拥有的。 Do I have a proper stack call?我有正确的堆栈调用吗?

INCLUDE Irvine32.inc

ExitProcess proto,dwExitCode:dword
.data
nValue DWORD 9
val DWORD 0
.code
fib PROC
    push ebp
    mov ebp, esp
    sub esp, 12
    mov EAX, [EBP+12]
    mov [EBP-8], ECX

    cmp ECX, 1 ;compare if greater than 1
    JG L1 
    L1: mov esp, ebp
        pop ebp
        ret
    JG L2
        L2: sub ecx, 1
        sub ecx, 2
        mov val, ecx
        push val
        call fib
     
fib ENDP

main PROC
    mov ecx, nValue
    push nValue
    call fib
main ENDP
END main

There is many errors and misunderstunding有很多错误和误解

  • val variable is useless val 变量没用
  • your working with input parameter and local variable is wrong.您使用输入参数和局部变量是错误的。 Better way is let assembler do his work.更好的方法是让汇编器做他的工作。 You can define input parameters and local variables like this.您可以像这样定义输入参数和局部变量。 All prolog and epilog code is inserted by assembler in right manner.所有 prolog 和 Epilog 代码都由汇编程序以正确的方式插入。 Please check final code by any debugger.请通过任何调试器检查最终代码。
    fib PROC param1:DWORD
    local localVar:DWORD

    mov EAX, param1
    mov localVar, EAX
    ....
    ret
    fib ENDP
  • at end of main missing also ExitProcess call.在 main 结束时还缺少 ExitProcess 调用。
  • recursive calculation of fibonaci numbers is also wrong.斐波那契数的递归计算也是错误的。
  • others errors - missing ret, and wrong condition jumps was already mentioned.其他错误 - 缺少 ret,并且已经提到了错误的条件跳转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM