rojcyk
rojcyk

Reputation: 247

Segmentation fault when calling function recursively

My task is to create a function which should calculate the arcsin for my input.

I tried to debug it using xcode. Everything works fine until return arcsin(new); is called. Then it's a segmentation fault: 11. I am not sure why but breakpoint at float arcsin(floatvalue){ ... }while running second cycle tells me that float old and float value is NAN.

float arcsin(float value){

     float old = value;
     float new = value + (0.5 * ((value * value * value)/3));
     float accurate = 0.00001;  

     if ((new - old) < accurate){
        return new;
     }

     else{
        return arcsin(new);
     }
}


int function_arcsin(int sigdig, float value){

    value = arcsin(value);
    printf("%.10e\n",value);

    return 0;
}

Upvotes: 4

Views: 19783

Answers (3)

user180247
user180247

Reputation:

I'm pretty sure the segmentation fault is caused by too-deep recursion. Although many compilers can optimise a lot of recursive code into iterative code, some can't, and it's quite common with e.g. debug options to disable this.

Conversion to an iterative form would stop the segfault - but, unless I miss my guess, give an infinite loop instead. I wouldn't expect a working recursive solution to be a problem here, unless you were testing with values out of the range the approximation converges with - in this case, my first guess is that inputs in the range -pi to +pi should be OK for any usable arcsin approximation.

I'm not familiar with the iterative approximation of arcsin, and my google-fu hasn't turned up the answer yet, but I suspect you have the calculation in the float new = ... line wrong.

I found this link...

Link

It's not that helpful - your code isn't suggestive of either approach described.

Upvotes: 0

Tio Pepe
Tio Pepe

Reputation: 3089

I tested your program and saw that never ends looping:

((new - old) < accurate)  // never is true

if you try with numbers > 0, reaches nan in 10 iterations. With numbers < 0, continue for thousands of times and causes too-deep recursion.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

A seg fault occurs when the call stack gets too big - i.e. too many levels of recursion.

In your case, this means the condition (new - old) < accurate will always evaluate to false - well, maybe not always, but enough times to bloat the call stack.

Testing your code I see that new(probably not a good variable name choice) keeps growing until it exceeds the limits of float. Your algorithm is probably wrong.

Upvotes: 5

Related Questions