简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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