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
alandeaxare two independent registers, but actually,alis just the lowest byte ofeax, so you were using the same register for two different things at the same time. Use another register likeedxas your array index instead ofeax.Also, you're almost certainly not running in 16-bit mode, so
loopwon't just checkcx, so the high bits of it will make the loop run more times than you want. Domov ecx, ninstead and also.long 5instead of.word 5. (Or you could useloopw l1instead ofloop l1if you're on 32-bit and really want to stick with justcxfor some reason.)