assemblyx86gnu-assemblerattcdecl

Swapping two int pointers in assembly x86


I want to swap two int pointers.

I can do it in C like this

void swap(int* a, int* b)
    int temp = *a;
    *a = *b;
    *b=temp;

Now I'm trying to do it in assembly but, and bear with me, I don't understand why this doesn't work

push %ebp
mov %esp,%ebp   

mov 8(%ebp), %ecx       #a 
mov 12(%ebp), %ebx      #b

mov (%ecx), %eax        #move o a para temp
mov (%ebx), %ecx        #move o b para o a
mov (%eax), %ebx        #move o temp para o b

mov %ebp, %esp
pop %ebp
ret

Can someone explain what I'm doing wrong?


Solution

  • As Weather Vane said, the C code you have shown is not swapping two int pointers. It is swapping two ints pointed by two int pointers.

    But in your assembly you appear to be trying to swap two ints pointed by two int pointers, so your code is not an entirely lost cause.

    Study this to understand what it does, and then give it a try:

    mov (%ecx), %eax
    mov (%ebx), %edx
    mov %edx, (%ecx)
    mov %eax, (%ebx)