问题描述
#include<iostream>
using namespace std;
int Fun(int x)
{
int sum=1;
if(x>1)
sum=x*Fun(x-1);
else
return sum;
}
int main()
{
cout<<Fun(1)<<endl;
cout<<Fun(2)<<endl;
cout<<Fun(3)<<endl;
cout<<Fun(4)<<endl;
cout<<Fun(5)<<endl;
}
此函数用于计算整数的阶乘。在 x> 1
的分支中,函数 Fun
没有返回值。所以这个函数不应该返回正确的答案。
This function is to compute the factorial of an integer number. In the branch of x>1
,there is no return value for function Fun
. So this function should not return correct answer.
但是当 fun(4)
正确的答案是意外。为什么?
But when fun(4)
or some other examples are tested, the right answers are got unexpectedly. Why?
此函数的汇编代码是(call Fun(4)):
0x004017E5 push %ebp
0x004017E6 mov %esp,%ebp
0x004017E8 sub $0x28,%esp
0x004017EB movl $0x1,-0xc(%ebp)
0x004017F2 cmpl $0x1,0x8(%ebp)
0x004017F6 jle 0x40180d <Fun(int)+40>
0x004017F8 mov 0x8(%ebp),%eax
0x004017FB dec %eax
0x004017FC mov %eax,(%esp)
0x004017FF call 0x4017e5 <Fun(int)>
0x00401804 imul 0x8(%ebp),%eax
0x00401808 mov %eax,-0xc(%ebp)
0x0040180B jmp 0x401810 <Fun(int)+43>
0x0040180D mov -0xc(%ebp),%eax
0x00401810 leave
0x00401811 ret
b $ b
可能是这个原因:sum的值保存在寄存器 eax
中,返回值保存在 eax
,因此 Fun
返回正确的结果。
May be this is the reason: The value of sum is saved in register eax
, and the return value is saved in eax
too, so Fun
return the correct result.
推荐答案
通常,EAX寄存器用于存储返回值,ad也用于执行其他操作。
Usually, EAX register is used to store return value, ad it is also used to do other stuff as well.
你可以使用-S()函数,这个函数返回一个返回值,选项生成汇编代码,并在ret指令之前查看EAX发生了什么。
You can use the -S option to generate assembly code and see what happened to EAX right before the "ret" instruction.
这篇关于混淆了函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!