-1

I am new to Intel x86 assembly - this is actually the first program I am writing for it.

I am trying to use a loop that is similar to this:

mov ecx,5
numLoop:
[OTHER CODE - DOESN'T OVERWRITE ECX]
loop numLoop

This looks fine to me, however it just loops forever in the output and I cannot figure out why. I do not alter the value of ECX at all during the extra code.

nrz
  • 10,435
  • 4
  • 39
  • 71
PotWashMike
  • 199
  • 1
  • 2
  • 8
  • 1
    Show the code in between, you properly have some `call` to a function that changes `ecx`. –  Nov 01 '13 at 23:48
  • @BSH, all I call is printf and scanf. Could either of these affect it? – PotWashMike Nov 01 '13 at 23:53
  • Yes they do, some functions may save all the values of the registers on the stack first, but to be safe, save the value of the register first before you call it. –  Nov 01 '13 at 23:59
  • 1
    `printf` and `scanf` uses `cdecl` convention. That means `eax`, `ecx`, `edx` may be clobbered after function call. – greatwolf Nov 02 '13 at 05:43

1 Answers1

1

Little trick: When you use loop you should push ecx to stack before your code and than before loop call you should pop it out from stack like that.

mov ecx,5
numLoop:
push ecx
[OTHER CODE - DOESN'T OVERWRITE ECX]
pop ecx
loop numLoop
yilmazburk
  • 907
  • 9
  • 17
  • If the code *actually* doesn't overwrite ECX, you don't need push/pop. If it does (e.g. a function call), you should pick a different register, like EBX or ESI, and use `dec ebx / jnz` instead of `loop`. push+pop+loop is 4 bytes, vs. 3 bytes for dec+jnz, so `loop` still loses on the only thing its good for (code size, [not speed](https://stackoverflow.com/questions/35742570/why-is-the-loop-instruction-slow-couldnt-intel-have-implemented-it-efficiently)) if you have to push/pop. – Peter Cordes Oct 27 '21 at 13:32