用汇编语言打印数组元素

时间:2013-01-11 13:22:36

标签: c assembly nasm

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

2 个答案:

答案 0 :(得分:2)

  1. 显然你想把两个参数传递给printf。然后你必须把它们都推(你似乎认为其中一个是在EAX中传递的,但事实并非如此)。
  2. C函数对clobber ECX是免费的,所以你应该保存并恢复它(你现在没有使用其他调用者保存的寄存器,但现在是时候阅读更多有关X86调用约定的内容了。)

答案 1 :(得分:0)

我找出了问题的解决方案。所以我在这里发帖给其他人

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