【发布时间】:2019-05-30 16:26:21
【问题描述】:
我需要弄清楚为什么在这个程序中什么都没有交换。该程序从一个单独的 C 程序中获取一个包含 4,5,1,3,2 的整数数组,并将其返回排序后。
我尝试修改了一些跳转命令,但没有任何效果。
.global myarray
.data
myarray:
lea (%rdi),%r8 #load array to register
mov %rsi,%r12 #load array size to register
mov $0,%r10 #initialize index
sort:
mov (%r8, %r10, 8), %rax #store array[i] in rax
inc %r10 #i++
mov (%r8, %r10, 8), %rdx #store array[i+1] in rdx
cmp %rax, %rdx #see if rdx is less than rax
jle swap #if rdx < rax, swap them
swap:
cmp %r12, %r10 #check if still in array bounds
je check #if we are at the end, check if sorted
dec %r10 #i--
mov %rdx, (%r8, %r10, 8) #move array[i+1] into array[i]
inc %r10 #i++
mov %rax, (%r8, %r10, 8) #move array[i] into array[i+1]
jmp check
check:
mov $0, %r14 #temporary index in r14
mov (%r8, %r10, 8), %eax #temporarily store array[i] in eax
inc %r14 #i++
mov (%r8, %r10, 8), %ebx #temporarily store array[i+1] in ebx
cmp %eax, %ebx #check if ebx is less than eax
jle sort #if ebx < eax, swap
cmp %r12, %r14 #check if still in array bounds
ret
预期结果是返回的数组排序; 1,2,3,4,5
【问题讨论】:
-
dec/incr10 围绕内存引用作为寻址模式的一部分的位移会更简单:-8(%r8, %r10, 8)。简化代码的局部小部分可以使调试时更容易看到全局,而不会迷失在混乱中。 (使用 GDB 或任何其他调试器来单步执行您的代码。)