2013-01-11 50 views
-1

我已经在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 

回答

0

我必须弄明白我problem.So我张贴在这里的其他人

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 
的解决方案
2
  1. 显然要设置两个参数传递给printf的。然后你必须将它们都推送(你似乎认为其中一个是通过EAX传递的,但事实并非如此)。 (你现在没有使用其他调用者保存的寄存器,但是现在是时候阅读更多关于X86调用约定的知识)。C函数可以自由地打开ECX,所以你应该保存和恢复它。