【发布时间】:2021-07-18 23:13:41
【问题描述】:
我正在尝试在汇编中编写递归斐波那契序列,但由于某种原因它无法正常工作。
没有报错,但是输出的编号总是错的。
section .bss
_bss_start:
; store max iterations
max_iterations resb 4
_bss_end:
section .text
global _start
; initialise the function variables
_start:
mov dword [max_iterations], 11
mov edx, 0
push 0
push 1
jmp fib
fib:
; clear registers
mov eax, 0
mov ebx, 0
mov ecx, 0
; handle fibonacci math
pop ebx
pop eax
add ecx, eax
add ecx, ebx
push eax
push ebx
push ecx
; incriment counter / exit contitions
inc edx
cmp edx, [max_iterations]
je print
; recursive step
call fib
ret
print:
mov eax, 1
pop ebx
int 0x80
例如,上面的代码打印的值是 79 而不是 144(第 11 个斐波那契数)。
或者,如果我做
mov dword [max_iterations], 4
然后上面的代码打印 178 而不是 5(第 5 个斐波那契数)。
有人有想法吗?
K
【问题讨论】:
-
错了怎么办?总是0?对于适合 Linux 进程的 1 字节退出状态的小数字是否正确,而对于较大的数字则截断? (mod 256)minimal reproducible example 需要这样的详细信息,以便人们知道他们正在寻找什么样的错误。
-
对,对不起,会更新的
-
您已将
max_iterations声明为单个字节的存储空间,但使用它时就像有 4 个字节一样。 -
您将
max_iterations声明为 1 个字节,然后将其视为 DWORD:mov dword [max_iterations], 11 -
fib函数所做的第一件事是从堆栈中弹出内容,这意味着它将删除返回地址。您不应该弹出函数参数,只需正常从内存中读取它们(或使用寄存器)。
标签: recursion assembly x86 fibonacci