Accessing "array" data in GNU assembler using Intel syntax

332 Views Asked by At

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.

1

There are 1 best solutions below

5
On

You seem to think al and eax are two independent registers, but actually, al is just the lowest byte of eax, so you were using the same register for two different things at the same time. Use another register like edx as your array index instead of eax.

Also, you're almost certainly not running in 16-bit mode, so loop won't just check cx, so the high bits of it will make the loop run more times than you want. Do mov ecx, n instead and also .long 5 instead of .word 5. (Or you could use loopw l1 instead of loop l1 if you're on 32-bit and really want to stick with just cx for some reason.)