Segmentation fault using recursion to find factorial

• 02-22-2009
kapok
Segmentation fault using recursion to find factorial
Noob here.
The title says it all.

Code:

```//using recursion to find the factorial of an entered number #include <iostream> using namespace std; int x; int solution; int factorial( int counter ) //factorial finding function { if ( x < counter )         {         factorial ( x + 1 ); //starts at one, runs the function up until x == the entered number.         } solution = solution * x; //with the exit of every function, solution is multiplied by the value of the argument. if ( solution > counter ) //so lets say the numbered entered was 4. it would run the function of 1, 2, 3 than solution (set equal to 4 already) is multiplied by 3, 2, 1.         {         if ( x == 1 ) { return solution; } //the function == 1 when it starts and when it ends. this tid bit makes sure not to return solution when it starts.         } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main() { x = 1; int number; int output; cin >> number; solution = number; //so that the function works multiplying all numbers less than the entered value output = factorial ( number ); //runs the function with the entered number. cout << output << endl; }```
The above code gives me compiles fine but gives me a segmentation fault when I run it.
Any ideas as to why?
• 02-22-2009
matsp
Your code is recursive, but I can almost guarantee that it will not produce the right result.

Certainly this looks VERY wrong:
Code:

```if ( solution > counter ) ...```
You should not use global variables for recursive functions, it causes all sorts of strange problems.

It most likely seg-faults because some condition to exit the recursion is never met - e.g. x is always a constant value?

--
Mats
• 02-22-2009
BMJ
Wow that's an interesting use of globals for a factorial function...

Here's an example of doing what you're trying to do:
Code:

```#include <iostream> using namespace std; int factorial(int x) {     if (x == 1)     {         return 1;     }     return (x * factorial(x - 1)); } int main() {     int number;     int output;     cin >> number;     output = factorial(number);     cout << output << endl; }```