I am tasked to write a GNU assembly program using Intel syntax which counts numbers in array which are <= 6
I came up with the following code:
.intel_syntax noprefix
.data
n: .word 5
a: .word 1, 6, 7, 4, 8
r: .word 0
.text
.global main
main:
mov cx, n
mov al, 0
mov eax, 0
l1: cmpw [a+eax*2], 6
ja l2
inc al
l2: inc eax
loop l1
mov r, al
ret
However while debugging it with GDB it seems to output 8 to variable r
which is incorrect for given data.
You seem to think
al
andeax
are two independent registers, but actually,al
is just the lowest byte ofeax
, so you were using the same register for two different things at the same time. Use another register likeedx
as your array index instead ofeax
.Also, you're almost certainly not running in 16-bit mode, so
loop
won't just checkcx
, so the high bits of it will make the loop run more times than you want. Domov ecx, n
instead and also.long 5
instead of.word 5
. (Or you could useloopw l1
instead ofloop l1
if you're on 32-bit and really want to stick with justcx
for some reason.)