【发布时间】:2018-10-24 16:15:37
【问题描述】:
我有一个交换两个数字的C 代码。
#include<stdio.h>
void swap(int,int);
void main( )
{
int n1,n2;
printf("Enter the two numbers to be swapped\n");
scanf("%d%d",&n1,&n2);
printf("\nThe values of n1 and n2 in the main function before calling the swap function are n1=%d n2=%d",n1,n2);
swap(n1,n2);
printf("\nThe values of n1 and n2 in the main function after calling the swap function are n1=%d n2=%d",n1,n2);}
void swap(int n1,int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
printf("\nThe values of n1 and n2 in the swap function after swapping are n1=%d n2=%d",n1,n2);
}
我已经使用objdump 对其进行了反汇编,并试图找出交换操作在机器级别是如何发生的。我认为这是交换功能。
000006b4 <swap>:
6b4: 55 push %ebp
6b5: 89 e5 mov %esp,%ebp
6b7: 53 push %ebx
6b8: 83 ec 14 sub $0x14,%esp
6bb: e8 37 00 00 00 call 6f7 <__x86.get_pc_thunk.ax>
6c0: 05 0c 19 00 00 add $0x190c,%eax
6c5: 8b 55 08 mov 0x8(%ebp),%edx
6c8: 89 55 f4 mov %edx,-0xc(%ebp)
6cb: 8b 55 0c mov 0xc(%ebp),%edx
6ce: 89 55 08 mov %edx,0x8(%ebp)
6d1: 8b 55 f4 mov -0xc(%ebp),%edx
6d4: 89 55 0c mov %edx,0xc(%ebp)
6d7: 83 ec 04 sub $0x4,%esp
6da: ff 75 0c pushl 0xc(%ebp)
6dd: ff 75 08 pushl 0x8(%ebp)
6e0: 8d 90 c0 e8 ff ff lea -0x1740(%eax),%edx
6e6: 52 push %edx
6e7: 89 c3 mov %eax,%ebx
6e9: e8 72 fd ff ff call 460 <printf@plt>
6ee: 83 c4 10 add $0x10,%esp
6f1: 90 nop
6f2: 8b 5d fc mov -0x4(%ebp),%ebx
6f5: c9 leave
6f6: c3 ret
我想知道交换操作是如何在寄存器中发生的,我知道它必须是这样的。
push eax
mov eax, ebx
pop ebx
但我看不到类似的东西。由于我对这些事情不熟悉,有人可以帮我理解这是如何发生的。 Full output of the objdump is here.
【问题讨论】:
-
这个练习的目的是什么?
-
SO 最适合特定问题。 “难以理解每条指令在做什么”的解决方案是查找汇编教程并阅读它。
-
你的程序不交换号码顺便说一句。使用指向
n1和n2的指针,例如scanf -
怎么读?小心。并访问godbolt.com 并记住编译器可能会完全优化您的代码并只留下具有副作用的语句,因此汇编中可能没有任何交换代码。
标签: c disassembly objdump