递归除了会引起无限循环,还有可能引起堆栈溢出。
如下面一个计算阶乘的递归函数:
unsigned int Fact (unsinged int i)
{
int iRet = 1;
if (i <= 1) return iRet ;
iRet = i * Fact (i - 1);
return iRet;
}
考虑一下:
Fact (100000000);
1M = 1047586
则它会申请 4 * 100000000 = 381M 或更多。
已经远远超出了线程1M的堆栈大小。
所以要使用循环替代递归。