segmentation fault on a recursive function

南楼画角 提交于 2021-02-10 18:43:20

问题


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

回答1:


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;



回答2:


Infinite recursion: The recursive call is executed unconditionally, and so the call stack grows until an error stops it.

This is a stack overflow.




回答3:


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. So you've got infinite recursion.




回答4:


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. what you probably want to do it return 1 if m = 0 instead of going through the method.



来源:https://stackoverflow.com/questions/8202445/segmentation-fault-on-a-recursive-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!