ihm
ihm

Reputation: 1863

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

Upvotes: 1

Views: 6288

Answers (4)

01d55
01d55

Reputation: 1912

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

This is a stack overflow.

Upvotes: 3

bshields
bshields

Reputation: 3593

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.

Upvotes: 2

Lol4t0
Lol4t0

Reputation: 12547

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;

Upvotes: 7

OSH
OSH

Reputation: 2937

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.

Upvotes: -1

Related Questions