Search code examples
c++xcodeexc-bad-access

EXC_BAD_ACCESS in simple c++ XCODE program


I'm new to c++ and I'm trying to make a calculator. I designed this function for the purpose of getting factorial of a number:

     int factorial(int num1) {
    int sum;
    if (num1 == 1) {
        sum = 1;
    }
    else {
        sum = factorial((num1 - 1) * num1);
    }

    return sum;
}

Whenever I try and compile this, however, I get the error EXC_BAD_ACCESS on the

int factorial(int num1)

Any idea what's going on? I'm using XCODE.


Solution

  • Your definition leads to an infinite recursion whenever num1 is not 1.

    Do the maths yourself:

      factorial(2)
    = factorial((2-1) * 2)
    = factorial(2)
    = factorial((2-1) * 2)
    = ...
    

    or

      factorial(3)
    = factorial((3-1) * 3)
    = factorial(6)
    = factorial((6-1) * 6)
    = factorial(30)
    = ...
    

    The recursive definition of the factorial function is not

    factorial(n) = factorial((n - 1) * n)
    

    it is

    factorial(n) = n * factorial(n - 1)
    

    (And the factorial is not a sum, but a product.)