Search code examples
cassemblyx86-64swap

Swapping 2 integers in assembly x86


I have an integer pointer pointing to the start of an array of ints and I'm trying to swap two values in assembly x86. This is the code I have:

movq (%rdi,%rcx,4),%r8     # SWAP
movq 4(%rdi,%rcx,4),%r9   
movq %r9,(%rdi,%rcx,4)
movq %r8,4(%rdi,%rcx,4)

rdi contains the pointer and the address calculations for the two values are correct (rcx is just 0 in the first iteration), however, this is what happens when I do the swap:

(gdb) x/5wd $rdi
0x602010:    31    1    2    3
0x602020:    0
(gdb) x/5wd $rdi
0x602010:    1     2    2    3
0x602020:    0
(gdb) x/5wd $rdi
0x602010:    1     31    2    3
0x602020:    0

As you can see the 3rd value is replaced by the swap of the first and second values and I can't understand why. Any suggestions about where I should be looking for my mistake?


Solution

  • movq moves 8 bytes, while you expect it to move 4.
    Use movl instead, with r8d and r9d (the low 32 bits of r8 and r9).

    Or the other way around, offset your memory accesses 8 bytes from one another instead of 4 to swap qwords.