Amit Singh Tomar
Amit Singh Tomar

Reputation: 8608

Why this Code causing infinte loop in assembly

I have a small piece of code in Assemby which is basiclly run through a loop and print values in reverse order but when I run, it goes to infinte loop.Below is the code .

section .data
x db "value=%d"
section .text
global main
extern printf
main:
mov eax, 10
well_done:
push eax
push x

call printf
add esp,8
dec eax
cmp eax ,0
jnz well_done
ret

Upvotes: 0

Views: 121

Answers (3)

user555045
user555045

Reputation: 64933

Since it's too long for a comment, I'll just put it here: what I meant with using a callee-save register is something like this

section .data
x db "value=%d"

section .text
global main
extern printf

main:
  mov ebx, 10
well_done:
  push ebx
  push x
  call printf
  add esp, 8
  dec ebx
  jnz well_done
  ret

Note that usually using ebx means that you should save ebx on entry and restore it on exit, but because this is main we get away with not doing that.

Upvotes: 1

Amit Singh Tomar
Amit Singh Tomar

Reputation: 8608

Thanks Everyone for the help .This is how I did as sugested by Harold.Thanks Harold

section .data
x db "value=%d"
section .text
global main
extern printf
main:
mov ebx, 10
well_done:
push ebx
push x

call printf
add esp,4
pop ebx
dec ebx
cmp ebx ,0
jnz well_done
ret

Upvotes: 0

Devolus
Devolus

Reputation: 22094

When you call a function you must be sure which registers are used. If you call a C function eax can be used for whatever the function needs it, so you must push eax before you execute the function, and after it returned you can pop it.

section .data
x db "value=%d"
section .text
global main
extern printf
main:
mov eax, 10
well_done:
push eax   <- save the counter
push eax   <- argument for printf
push x

call printf
add esp,8   <- clears the stack with the arguments for printf
pop eax   <- restore the counter
dec eax
cmp eax ,0
jnz well_done
ret

Upvotes: 1

Related Questions