0

As per the question, how do I index arrays in nasm assembly that are inside a function? I always get the error invalid effective address whenever I compile my code, and based on the searches I have done, it has something to do with the registers I use when I index. Even then, I am still not sure what registers to use given the different architectures of assembly.

get_largest:

mov rcx, 5
mov bl, 0
mov al, 0

neg_loop:
cmp rcx, 0
je check_neg
cmp dword[rdi+al*2], 0
jl incbl
inc al
jmp neg_loop
incbl:
inc al
inc bl
jmp neg_loop

check_neg:
cmp bl, 5
jl check_largest
mov rsi, 1
mov rdx, -1
jmp return

check_largest:
mov rsi, 0
mov rcx, 5
mov al, 0
mov bl, 0

large:
cmp rcx, 0
je greatest
cmp dword[rdi+al*2], bl
jg larger
inc al
jmp large

larger:
mov bl, dword[rdi+al*2]
inc al
jmp large

greatest:
mov rdi, bl

return:
    ret 

Here is my function and the compile error occurs at cmp dword[rdi+al*2], 0

honj - t
  • 87
  • 8
  • 1
    The index register should be 64 bits. Try replacing all your `al` with `rax`. – Nate Eldredge May 25 '21 at 22:33
  • 2
    But also using a scale of 2 doesn't make sense with a dword-size `cmp`. What size of data is this array supposed to contain? – Nate Eldredge May 25 '21 at 22:34
  • Hi, I only realized now but dword is supposed to be word LOL. Ill try your suggestions too. Thanks – honj - t May 25 '21 at 22:47
  • Also, sorry @NateEldredge but given that the array is word-size not double-word size, should I still use rax as the index? – honj - t May 25 '21 at 22:58
  • 2
    Yes, always. Think about what is done: the machine computes an address by multiplying rax by 2 and adding to rbx. If rax weren't 64 bits, you'd be adding two registers of different sizes, and that's not supported. On a similar principal, your later instructions like `mov rdi, bl` and `mov bl, dword...` are also not valid: operand sizes have to match. You can't move a byte into a qword (unless you explicitly specify sign or zero extension with `movsx/movzx`, and you can't move a dword into a byte. – Nate Eldredge May 25 '21 at 23:00
  • Thank you for the in-depth reply. It was very helpful and actually made me understand arrays more (given that what I learned is quite barebones). I also noticed the mov rdi, bl... parts as well in the code as I forgot that operand sizes should always match when it comes to moving values. – honj - t May 25 '21 at 23:17

0 Answers0