Вопрос

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. When I execute my program, it goes in an infinite loop which only outputs 4. Why is EAX's value 4? Why is register EAX not increasing as it should?

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). Since that is less than 10, you loop up, add 1 (which makes it 4), print that, and repeat.

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:

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.

Другие советы

Always preserve EAX before using printf. printf destroys your EAX

inc eax
push eax
...call to printf
pop eax
cmp eax,10
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top