Reputation: 3418
I have this short piece of code, its purpose is to sum negative values and count positive ones, the vector is initialized else where
;sum all negative values and count positive values
;let eax hold sum and ebx hold number of positives
CALL crlf
mov ecx, VectorSize
mov eax, 0
mov ebx, 0
mov edx, 0
sumMe:
cmp Vector[edx * TYPE Vector], 0
jge pos
;neg
add eax, Vector[edx * TYPE Vector]
INC edx
loop sumMe
pos:
INC ebx
INC edx
loop sumMe
The piece of code works correctly except when a negative value is the last value in the array, even something like -1 -1 -1 -1 5
works. However if I have a negative value in the last location the program crashes.
Any help would be appreciated
Upvotes: 0
Views: 78
Reputation: 364483
Assuming there's a ret
or something at the end:
What does loop
do when ecx reaches zero: execution falls through. If the last element was negative, the loop
instruction that makes ecx
zero is followed by pos:
.
When loop
runs with ecx=0
to start with, ecx
wraps to 0xFFFFFFFF
and the jump is taken. loop
is like the bottom of a do{}while(--ecx);
.
All of this would be obvious if you used a debugger to single-step that last iteration, because you already know the problem is at the end of the array with a negative element.
Upvotes: 3