Question

I am having an issue with a MASM32 program. I am trying to get this code to work:

.DATA
alfa dword 9

.CODE
start:

MOV ecx, alfa
MOV eax, 0

L1: ADD eax, ecx
DEC ecx
LOOP L1
CALL WRITEINT

exit
END start

I have found that the problem is only within the loop, everything else works fine. Can some please help me get the loop to work correctly, it does not return a value and doesn't exit. Is this supposed to happen? Thank you all in advance!

Was it helpful?

Solution

You are decreasing ecx twice. The dec instruction will decrease it, and the loop instrucction also decreases it.

Either use

dec ecx
jne L1

or use

loop L1

The reason why it doesn't exit is the following

dec ecx ->  ecx = 8
loop l1 -> ecx = 7
dec ecx ->  ecx = 6
loop l1 -> ecx = 5
dec ecx ->  ecx = 4
loop l1 -> ecx = 3
dec ecx ->  ecx = 2
loop l1 -> ecx = 1

And here comes the catch!

dec ecx ->  ecx = 0   no condition
loop l1 -> ecx = 0xffffffff Loop will not break because it breaks on 0
dec ecx -> ecx = 0xfffffffe
loop l1 -> ecx = 0xfffffffd
...

... and so on. You get the idea. If you had used a debugger, you would have seen this after only a few iterations.

Actually ecx will reach 0 in this roundtrip, but it takes LONG time. :)

OTHER TIPS

LOOP already takes care of the decrement, so get rid of the DEC ECX, i.e. change:

DEC ecx
LOOP L1

to just:

LOOP L1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top