Don't really understand how arrays work in Assembly

时间:2016-10-20 18:52:30

标签: arrays assembly

I've just started learning Assembly and I got stuck now...

%include 'io.inc'

global main

section .text
main:
    ; read a
    mov eax, str_a
    call io_writestr
    call io_readint
    mov [nb_array], eax
    call io_writeln

    ; read b
    mov eax, str_b
    call io_writestr
    call io_readint
    mov [nb_array + 2], eax
    call io_writeln

    mov eax, [nb_array]
    call io_writeint
    call io_writeln
    mov eax, [nb_array + 2]
    call io_writeint

section .data
nb_array dw 0, 0
str_a db 'a = ', 0
str_b db 'b = ', 0 

So, I have a 2 elem sized array and when I try to print the first element, it doesn't print the right value. Although I try to print the second element, it prints the right value. Could someone help me understand why is this happening?

1 个答案:

答案 0 :(得分:3)

The best answer is probably "because there are no arrays in Assembly". You have computer memory available, which is addressable by bytes. And you have several instructions to manipulate those bytes, either by single byte, or by groups of them forming "word" (two bytes) or "dword" (four bytes), or even more (depends on platform and extended instructions you use).

To use the memory in any "structured" way in Assembly: it's up to you to write piece of code like that, and it takes some practice to be accurate enough and to spot all bugs in debugger (as just running the code with correct output doesn't mean much, if you would do only single value input, your program would output correct number, but the "a = " would be destroyed anyway - you should rather every new piece of code walk instruction by instruction in debugger and verify everything works as expected).

Bugs in similar code were so common, that people rather used much worse machine code produced by C compiler, as the struct and C arrays were much easier to use, not having to guard by_size multiplication of every index, and allocating correct amount of memory for every element.

What you see as result is exactly what you did with the memory and particular bytes (fix depends whether you want it to work for 16b or 32b input numbers, you either have to fix instructions storing/reading the array to work with 16b only, or fix the array allocation and offsets to accompany two 32b values).