NASM反转整数数组

时间:2015-02-09 22:28:40

标签: arrays assembly x86 stack nasm

从概念上讲,我试图将值推到堆栈上并在"对面"中弹出它们。订购。在实践中,我认为我这样做但我不确定。传递的数组在section .data中定义为array: dd 1, 2, 3, 4, 5, 6,并且大小作为int值传递(3 = 3个元素)。当我运行应用程序时,它链接和组装但数组不会反转。

push dword array
push dword [arrayLen]
call reverse
add esp, 8

; other stuff

reverse:
    push ebp                    ; setup stack
    mov ebp,esp 
    sub esp,0x40                ; 64 bytes of local stack space 

    ; put parameters into registers
    mov ebx, [ebp+12]           ; array
    mov edx, [ebp+8]            ; len

    ; set up loop
    mov ecx, 0

    ; push all the values onto the stack
    .loopPush:
        mov eax, 4
        mul ecx
        push dword [ebx]
        add ecx, 1
        cmp ecx, edx
            jl .loopPush
    mov ecx, 0

    ; pop all the values from the stack
    .loopPop:
        mov eax, 4
        mul edx
        pop dword [ebx+edx]
        add ecx, 1
        cmp ecx, edx
            jl .loopPop

    ; print the array
    push dword [ebp+12]
    push dword [ebp+8]
    call printArray
    add esp, 8

    .end:
        mov esp,ebp             ; undo "sub esp,0x40" above 
        pop ebp
        mov eax, ebx                ; return the reversed array
        ret 

打印功能可准确地打印我提供的任何内容,因此我大约90%确定打印时不会出现问题。提前谢谢!

1 个答案:

答案 0 :(得分:1)

首先阅读this以获取有关mul指令的信息。在更正了mul指令并在代码中使用结果后,一切正常。我更正你的代码如下:

section .data
    array:  dd 1, 2, 3
    arrayLen: dd 3

section .text
global main

main:
    push dword array
    push dword [arrayLen]
    call reverse
    add esp, 8


reverse:
    push ebp        ; setup stack
    mov ebp, esp
    sub esp, 0x40       ; 64 bytes of local stack space

    ; put parameters into registers
    mov ebx, [ebp + 12]           ; array
    mov edi, [ebp + 8]            ; len

    ; set up loop
    mov ecx, 0

; push all the values onto the stack
.loopPush:
    mov eax, 4
    mul ecx
    push dword [ebx + eax]
    inc ecx
    cmp ecx, edi
    jl .loopPush
    mov ecx, 0

; pop all the values from the stack
.loopPop:
    mov eax, 4
    mul ecx
    pop dword [ebx + eax]
    inc ecx
    cmp ecx, edi
    jl .loopPop

; print the array
    ;push dword [ebp+12]
    ;push dword [ebp+8]
    ;call printArray
    ;add esp, 8

.end:
    mov esp,ebp ; undo "sub esp,0x40" above                                                                     
    pop ebp
    mov eax, ebx    ; return the reversed array
    ret

抱歉,我必须对您的代码的某些部分发表评论。

相关问题