Assembly - Swap function - Why it will not work?

后端 未结 2 835
我在风中等你
我在风中等你 2021-01-27 21:50

I need to create a function that swaps the value of &x with the value of &y (meaning swap *(&y) and *(&x).

Swap:

    push EBP
    mov EBP,ESP
           


        
2条回答
  •  广开言路
    2021-01-27 22:19

    You don't actually reserve memory on the stack that you use when you access a dword at [EBP-4]. It can get overwritten by things like interrupt routines, signal handlers, asynchronously called procedures, whatever applies in your OS.

    The code should be like this instead:

    swap:
        push  EBP
        mov   EBP,ESP           ; make a traditional stack frame
    
        sub   ESP, 4         ; reserve memory for a local variable at [EBP-4]
    
        mov   EBX, [EBP+12]        ; ebx = &x
        mov   EAX, DWORD [EBX]     ; eax = x
        mov   DWORD [EBP-4], EAX   ; [ebp-4] = eax = x
        mov   EDX, [EBP+8]         ; edx = &y
        mov   EAX, DWORD [EDX]     ; eax = y
        mov   DWORD [EBX], EAX     ; *&x = y
        mov   EAX, DWORD [EBP-4]   ; eax = x reloaded from the local
        mov   DWORD [EDX], EAX     ; *&y = x
    
        leave          ; remove locals (by restoring ESP), restore EBP
    
        ret
    

    Also, make sure that you're passing as parameters the addresses of the variables x and y, not the values of the variables. push x+push y will pass the addresses of x and y in NASM but they will pass values of x and y in TASM and MASM.

提交回复
热议问题