4

for some reason, it used to work. but now i get a SIGFPE.....what's wrong?

#include "usefunc.h"

long factorial(long num) {
    if (num > 1) {
        long counter;
        long fact = 1;
        for (counter = num; counter > 0; counter--) fact *= counter;
        return fact;
    }
    else return 0;
}

long combinations(long n, long k) {
    return (factorial(n)) / (factorial(k)*factorial(n-k));
}

int main()
{
    printf("How many rows of Pascal\'s triangle should I print?\t");
    int rows = GetInteger();
    long pArray[rows][rows];
    int counter;
    int counter2;
    for (counter = 1; counter <= rows; counter++)
    {
        int y = rows-counter;
        for (; y > 0; y--) printf("    ");
        for (counter2 = 0; counter2 <= counter; counter2++)
        {
            /*

                    THIS IS AN OUTPUT

            */
            printf("%9.0lu", (long) combinations(counter, counter2));
            pArray[counter][counter2] = (long) combinations(counter, counter2);
        }
        /*

                    THIS IS AN OUTPUT

        */
        printf("\n");
    }
    return 0;
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
tekknolagi
  • 10,663
  • 24
  • 75
  • 119

2 Answers2

8

your factorial returns 0, which then can cause a divide-by-0 error. shouldn't it be returning 1?


jcomeau@intrepid:/tmp$ cat test.c; make test;./test
#include <stdio.h>
int main() {
 return printf("%f\n", 1L / 0);
}
cc     test.c   -o test
test.c: In function ‘main’:
test.c:3: warning: division by zero
Floating point exception
jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
  • A long divided by long is not a floating-point exception. And a better fix might be to add a check in `combinations` that `k >= 0 && k <= n`. – Ben Voigt Jun 04 '11 at 04:39
  • 4
    This is right — dividing an integer by zero will cause a `SIGFPE`. Interestingly, dividing a floating point number by zero will not cause a `SIGFPE`. – Dietrich Epp Jun 04 '11 at 04:41
6

I think it's your combinations function, which you haven't shown us, because none of the code you've given uses any floating-point whatsoever.


SIGFPE does not mean floating-point exception, even if that's where the name came from. @jcomeau has correctly identified why you're getting SIGFPE.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • @tekknolagi: Ok, I don't see any floating-point anywhere. But you have a bunch of useless casts. Also your "combinations" function is implemented naively, its internal variables will overflow long before the result does. – Ben Voigt Jun 04 '11 at 04:38