我在 nasm 程序集中编写了以下代码,用于在 scree 上打印数组元素。在此代码中没有编译错误,但我在屏幕上得到了垃圾值。
section .data
num1: dd 10, 20, 30, 40, 50, 10, 20, 30, 40, 50,300
total: dd 0
msg : dd "Value=%d",10,0
section .text
extern _printf
global _main
_main:
push ebp
mov ebp,esp
mov ebx,num1 ;point bx to first number
mov ecx,11 ;load count of numbers in ecx
mov eax,0
loop:
mov eax,[ebx]
push msg
call _printf
add ebx,4
sub ecx,1
jnz loop
mov esp,ebp
pop ebp
ret
解决方案
section .data
num1: dd 10, 20, 30, 40, 50, 10, 20, 30, 40, 50,300
total: dd 0
msg : dd "Value=%d",10,0
section .text
extern _printf
global _main
_main:
push ebp
mov ebp,esp
mov eax,10
mov ebx,num1 ;point bx to first number
mov ecx,0 ;load 0
loop:
;store the value because external function like printf modify the value
push ebx
push eax
push ecx
push DWORD [ebx]
push msg
call _printf
add esp,8
;restore thses values
pop ecx
pop eax
pop ebx
inc ecx
add ebx,4
cmp ecx,eax
jne loop
mov esp,ebp
pop ebp
ret