使用eax的Fasm循环不起作用

时间:2013-11-29 04:54:31

标签: loops assembly x86 fasm

我正在尝试在汇编中创建一个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"

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

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

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