Serena Qi
Serena Qi

Reputation: 121

nasm assembly for loop

I'm trying to build for loop, but it gives me infinite loop:

SECTION .data

i: dd 0
message: db "The number is %d",10,0
SECTION .text

extern printf
global main

main:
    push ebp
    mov ebp, esp

    mov eax, DWORD [i]
    mov ecx, DWORD 10

    L1:
        add eax, DWORD 1
        push eax
        push message
        call printf
        add esp, 8
        loop L1
    mov esp, ebp
    pop ebp

nasm gives me the output as The number is 18 infinitely. But if I put printf at the end of the code. It gives me the correct output

L1:
    add eax, DWORD 1
    loop L1

push eax
push message
call printf
add esp, 8

mov esp, ebp
pop ebp

Anyone knows where I did wrong?

Upvotes: 1

Views: 13006

Answers (1)

nneonneo
nneonneo

Reputation: 179392

ecx is the loop variable. It is typically caller-saved - that is, a function like printf is allowed to overwrite it and not restore the old value. Therefore, on return from printf, ecx will be garbage.

To fix this, you can add a push ecx before pushing arguments, then a pop ecx after the add esp removes the function arguments.

Upvotes: 4

Related Questions