views:

270

answers:

2

Hello,

I've been asked to create a simple loop in assembly language but I am having trouble as the loop doesn't end when it should, it continues in an infinite loop.

I need to give the ECX a variable which is taken by input, but in my code below even when I specify the counter directly is still falls into an infinite loop.

My code is here (UPDATED):

PasteBin Code

The code may contain errors other than the actual loop.

//Edited for explanation of the programs requirements...

The program needs to take an input "n" which will be used as the counter for the loop. I then take input "n" more numbers, when a number is positive I need to add that to the variable postot, when negative I need to add that to the variable negatot. After "n" numbers have been entered I print the results for each variable and the program exits.

Edit 2:

Fixed the loop problem by clearing the Stack correctly so I added:

     add esp,8

and:

next:   push ecx
     ...
pop ecx
loop next

Which fixed the loop problem.

A: 

I see two errors:

  • There's a JG positive in there AFTER you increment a stack pointer. Are you sure you want to check the result of fiddling with your stack frame, rather than the value of the number you entered?

  • jmp end doesn't: Right after end comes a loop next. I don't see any condition for terminating the loop.

Carl Smotricz
I thought the loop would end automatically if ECX is 0?
Anarchist
It should, you can always try sub ecx, 1 cmp ecx 0 je SOMEOTHERLABEL
Andres
+1  A: 

Ok, I got it. . . You read int the number from the user. Then on line 41 you either jump to line 47 or fall through to line 43.

If you go to line 43, you then reach line 45 which jumps to line 49(end). If instead, you went to line 47, you will fall through to line 49(end).

In both cases, you then loop back to line 29(next).

You expect your ecx register to decrement every time loop is reached, and for it to remain unchanged during the processing of the loop.

Have you tried pushing ecx at around line 29, and popping it right before you loop?

Andres
As a quick test of this, remove everything from lines 30 to 49. If it ever exits the loop, then you know something inside the loop is changing the value of ecx
Andres
It works when I remove everything, I can see in the Auto window (Visual Basic C++) the ECX counter decrementing.
Anarchist
Did you try pushing and popping ecx?
Andres
Yes and it worked, see my edit above. Thanks.
Anarchist