简体   繁体   English

递归函数上的分割错误

[英]segmentation fault on a recursive function

I simply want to test something. 我只是想测试一下。 I am wondering what I did wrong? 我想知道我做错了什么?

   #include <iostream>
   using namespace std;
   unsigned long pwr(unsigned long n, unsigned long m)
   {
          if(m == 0)
            n = 1;
          if(m == 1)
            n = n;
          n = pwr(n, m/2) * pwr(n, m/2);
          return n;
   }

   int main ()
   {
          unsigned long n(2), m(16);
          cout << pwr(n, m);
          return 0;
   }

output is 输出是

Segmentation fault

There is no exit from recursion. 递归没有退出。

You may wanted 你可能想要

          if(m == 0)
             n = 1;
          else if(m == 1)
             n = n;
          else 
             n = pwr(n, m/2) * pwr(n, m/2);
          return n;

You're not ending the recursion when you hit your base case. 遇到基本情况时,您不会结束递归。 Even when m == 0 or m == 1 are true, you still recursively call pwr . 即使当m == 0m == 1为true时,您仍然可以递归调用pwr So you've got infinite recursion. 因此,您具有无限递归。

Infinite recursion: The recursive call is executed unconditionally, and so the call stack grows until an error stops it. 无限递归:递归调用是无条件执行的,因此调用堆栈会不断增长,直到错误停止为止。

This is a stack overflow. 这是堆栈溢出。

you are dividing by 0: let's say m starts from 1, in the next iteration m = 1/2 = 0, and you will get the fault. 您被0除:假设m从1开始,在下一次迭代中m = 1/2 = 0,您将得到错误。 what you probably want to do it return 1 if m = 0 instead of going through the method. 如果m = 0而不是通过该方法,则可能要返回1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM