[英]Fasm loop using eax not working
I am trying to make a for loop in assembly where the EAX
register is set to 5, and increased until it is greater than 10. Each time it increases, it outputs it's current value.我试图在汇编中创建一个 for 循环,其中
EAX
寄存器设置为 5,并增加直到它大于 10。每次增加时,它都会输出它的当前值。 When I execute my program, it goes in an infinite loop which only outputs 4. Why is EAX
's value 4?当我执行我的程序时,它进入一个只输出 4 的无限循环。为什么
EAX
的值是 4? Why is register EAX
not increasing as it should?为什么寄存器
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"
The output from printf
is returned in eax
which contains the number of characters printed: 3 in your case (the digit, CR, and LF). printf
的输出在eax
中返回,其中包含打印的字符数:在您的情况下为 3(数字、CR 和 LF)。 Since that is less than 10, you loop up, add 1 (which makes it 4), print that, and repeat.因为它小于 10,所以你循环,加 1(使它成为 4),打印出来,然后重复。
What you need to do is store eax ( push eax
) before setting up the printf
call, then restore it ( pop eax
) after printf
returns like:您需要做的是在设置
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
Or use a different register such as ebx
for your loop variable.或者为循环变量使用不同的寄存器,例如
ebx
。
Always preserve EAX before using printf.在使用 printf 之前始终保留 EAX。 printf destroys your EAX
printf 破坏了你的 EAX
inc eax
push eax
...call to printf
pop eax
cmp eax,10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.