Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 462
rojcyk Avatar asked Oct 26 '25 09:10

rojcyk


1 Answers

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.

like image 58
Luchian Grigore Avatar answered Oct 28 '25 00:10

Luchian Grigore