Home > Enterprise >  I'm getting a segmentation fault error in my program, but it is unclear how
I'm getting a segmentation fault error in my program, but it is unclear how

Time:11-16

From my understanding of segmentation faults, they occur when you try to access memory outside of the "space" of the program. My IDE says the exception occurs within in the first for loop where I perform the following operation: pi = w i * i; I don't understand how I am accessing memory that I shouldn't access. The program is supposed to compute pi, up to a given amount of digits, it is not yet complete. I was testing what I have so far when the error occurred. The code follows:

/// computes the continued fraction, recursivley
int w = 1;
static long double pi = 0;
long double continued_fraction(int k, int i){

    for(int i = 1; i <= k; i  ){
        pi  = w   i * i;
        w  = 2;
        pi /= continued_fraction(k, i  );
    }

    return pi;
}

/// continued fraction method to compute pi, up to a limit k
long double limit_fraction(int k){
    int i = 1;

    /// continued fraction method
    pi = 4 / continued_fraction(k, 1);

    return pi;
}

CodePudding user response:

Included code has infinitive recursion.

Lets call continued_fraction(1, 1). Then we enter for loop which redefines i and set it to 1 then first iteration when it does: continued_fraction(k, i ); it do: continued_fraction(1, 1) since post-increments provides old i.

This call is exactly same as first call, so recursion goes forever and you have stackoverflow - crash.

  • Related