Home > Software engineering >  Print array in Asembly x86
Print array in Asembly x86

Time:04-13

I have elements loaded in stack and I need to move them to array. My code looks like this:

%include "asm_io.inc"

segment .data
    array db 100 dup(0)
    length db 0
    
segment .text
    global  _asm_main
    extern getchar

_asm_main:
    enter    0, 0
    pusha

    call getchar
char_loop:
    mov ebx,10
    sub eax, '0'
    mul ebx
    mov ebx, eax
    call getchar
    sub eax, '0'
    add eax, ebx
    push eax
    inc BYTE[length]
    call getchar
    cmp eax, 10
    je fill_array
    cmp eax, 13
    je fill_array
    cmp eax, 32
    je skip_spaces
    jmp char_loop
skip_spaces:
    call getchar
    cmp eax, 32
    je skip_spaces
    jmp char_loop

fill_array:
    mov ecx, [length]
    mov ebx, array
l1:
    pop eax
    mov [ebx], eax ; should be al instead of eax
    inc ebx
    call print_int
    call print_nl
    loop l1
print_array:
    mov ecx, [length]
    mov ebx, array
l2:
    mov eax, [ebx] ; should be al instead of eax
    call print_int
    call print_nl
    inc ebx
    loop l2

_asm_end:
    call print_nl
    popa
    mov eax, 0
    leave
    ret 

print_int in asm_io.asm is

print_int:
        enter   0,0
        pusha
        pushf

        push    eax
        push    dword int_format
        call    _printf
        pop     ecx
        pop     ecx

        popf
        popa
        leave
        ret

Where int_format is int_format db "%i",0

Length and values in stack are correct, I had them printed but when I try to print array only last value is correct. Other values are random numbers. I tried combinations of registers of different sizes but it did not work. I think that error has to do something with size of registers or size of array.

CodePudding user response:

Answer here: As @xiver77 said in comments I was writing into array 4 bytes instead 1 byte. One element in array has 1 byte and I tried to write 4 bytes. That creates overflow of bites and change other elements in array. Instead mov [ebx], eax should be mov [ebx], al and mov eax, [ebx] for printing should be mov al [ebx].

  • Related