繁体   English   中英

使用 eax 的 Fasm 循环不起作用

[英]Fasm loop using eax not working

我试图在汇编中创建一个 for 循环,其中EAX寄存器设置为 5,并增加直到它大于 10。每次增加时,它都会输出它的当前值。 当我执行我的程序时,它进入一个只输出 4 的无限循环。为什么EAX的值是 4? 为什么寄存器EAX没有增加?

include 'include/macro/import32.inc'
format PE console
entry start

section '.text' code readable executable

start:

mov eax,5
loop1:
    inc eax
    push eax
    push msg2
    call [printf]
    cmp eax,10
    jb loop1

call [getchar]
push 0
call [exit]

section '.data' data readable writable
msg2  db "%i",0dh,0ah,0

section 'idata' import data readable
library msvcrt,"msvcrt.dll"
import msvcrt,printf,"printf",getchar,"getchar",exit,"exit"

printf的输出在eax中返回,其中包含打印的字符数:在您的情况下为 3(数字、CR 和 LF)。 因为它小于 10,所以你循环,加 1(使它成为 4),打印出来,然后重复。

您需要做的是在设置printf调用之前存储 eax ( push eax ),然后在printf返回后恢复它 ( pop eax ),如下所示:

loop1:
    inc  eax
    push eax        ; store eax
    push eax
    push msg2
    call [printf]
    add  esp,8      ; clean the stack from the printf call 
    pop  eax        ; restore eax
    cmp  eax,10
    jb   loop1

或者为循环变量使用不同的寄存器,例如ebx

在使用 printf 之前始终保留 EAX。 printf 破坏了你的 EAX

inc eax
push eax
...call to printf
pop eax
cmp eax,10

暂无
暂无

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

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