2013-11-29 47 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