2013-11-29 45 views
0

我试图做一个for循环的程序集,其中EAX寄存器设置为5,并且增加到大于10为止。每次增加时,它都输出它的当前值。当我执行我的程序时,它会进入无限循环,只输出4.为什么EAX的值是4?为什么寄存器EAX没有增加,因为它应该?使用eax不工作的fasm环路

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" 

回答

1

printf从输出在eax包含打印的字符的数目被返回:3你的情况(数字,CR,和LF)。因为那少于10,你循环,加1(这使它4),打印并重复。

你需要做的是店EAX(push eax)建立printf呼叫之前,再恢复它(pop eaxprintf后的回报,如:

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您循环变量。

+0

你也没有清理打印参数,所以它们堆积在栈上,你的弹出不会弹出正确的东西。 –

+0

@ RaymondChen:我完全隔开那一个。感谢您的提醒。 – DocMax

+0

我已经使用了一个辅助寄存器来保存您建议的值,并且它像一个魅力一样工作。你的例子也很棒。 – Johnathan

0

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

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