在Asmbly x86中打印阵列



我在堆栈中加载了元素,需要将它们移动到数组中。我的代码如下:

%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 

asm_io.asm中的print_int

print_int:
enter   0,0
pusha
pushf
push    eax
push    dword int_format
call    _printf
pop     ecx
pop     ecx
popf
popa
leave
ret

其中int_formatint_format db "%i",0

堆栈中的长度和值都是正确的,我已经打印了它们,但当我尝试打印数组时,只有最后一个值是正确的。其他值是随机数。我尝试了不同大小寄存器的组合,但没有成功。我认为这个错误与寄存器的大小或数组的大小有关。

请在此处回答:正如@xiver77在评论中所说,我在数组中写入了4个字节,而不是1个字节。数组中的一个元素有1个字节,我尝试写入4个字节。这会造成比特溢出并更改数组中的其他元素。相反,mov [ebx], eax应该是mov [ebx], al,并且用于打印的mov eax, [ebx]应该是mov al [ebx]

最新更新