Segmentation fault in C recursive Combination (nCr)
PLease help me out here. The program is supposed to recursively find out the combination of two numbers. n开发者_StackOverflow中文版Cr = n!/ (r!(n-r)! ). I'm getting this error message when i compile it on GCC.
Here's what the terminal shows:
Enter two numbers: 8 4 Segmentation fault
(Program exited with code:139)
The code is given here:
#include<stdio.h>
float nCr(float, float, float);
int main()
{
float a, b, c;
printf("Enter two numbers: \n");
scanf("%f%f", &a, &b);
c = nCr(a, b, a-b);
printf("\n%.3f", c);
return 0;
}
float nCr(float n, float r, float p)
{
if(n<1)
return (1/(p*r))*(nCr(1, r-1, p-1));
if(r<1)
return (n/(p*1))*(nCr(n-1, 1, p-1));
if(p<1)
return (n/r)*(nCr(n-1, r-1, 1));
return ( n/(p*r) )*nCr(n-1, r-1, p-1);
}
Since nCr doesn't have any return statement that is not recursive, it will recurse infinitely. Since this will cause the stack to grow infinitely, you get your segmentation fault.
Basically a recursive function should always have at least one possible path through the function which does not recurse. Otherwise you have infinite recursion.
- Why are you using floats? Combinations only deal with integers... Use a formula that doesn't involve floating point arithmetic.
- No matter what happens, a recursive call is being made. This means that you will have infinite recursion. This is why the segmentation fault happens. I suggest you read the link I gave you and implement your program using one of the formulas given there. Pay attention to the base cases.
You surely fall into infinite recursion to get this Segmentation Fault. You essentially don't have base case to stop the recursion as sepp2k mentioned.
Have you tried debugging the crash? You can use this page as a reference. If you can post information about the crash (stack trace, etc.) that would help both yourself and the SO community in figuring out the problem.
精彩评论