AxMa
AxMa

Reputation: 31

Segmentation fault with recursive factorial implementation

Now I am practicing using Vim on Linux. I made a simple code like this

#include <stdio.h>

int factorial(int n){
   if (n<0) { return 0; }
   else if (n==0) { return 1; }
   else { return n * factorial(n); }
}

int main(void){
   int n = 0;

   printf("Put n value : ");
   scanf("%d", &n);  /* non-OP inserted ";" to help people focus on the problem */

   printf("%d! = %d\n", n, factorial(n));

   return 0;
}

When I put -1 and 0, it works. They return 0 and 1. However, when I put positive integer values on n, it didn't work. I tried to find out the reason so I used gdb,
but it just said like this :

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400620 in factorial ()

What's wrong with my code? I even cannot understand the point.

Upvotes: 0

Views: 210

Answers (2)

haccks
haccks

Reputation: 106052

You code is causing stack overflow. In the given function n is never decremented. Last statement should be

else { return n * factorial(n-1); }

Upvotes: 3

user9614249
user9614249

Reputation:

When n > 0 your recursive program never terminates. The value of n is never decremented and so it continues running recursively until your run out of memory.

It should be return n * factorial(n-1);

Upvotes: 4

Related Questions