Segmentation fault when calling function recursively

14,722

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.

Share:
14,722

Related videos on Youtube

rojcyk
Author by

rojcyk

Updated on June 04, 2022

Comments

  • rojcyk
    rojcyk almost 2 years

    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;
    }
    
    • bitmask
      bitmask over 12 years
      @spicavigo: That's C, not C++, so it's fine.
    • Matvey Aksenov
      Matvey Aksenov over 12 years
      maybe your formula is wrong? it's dying on 174510th call to itself on my machine.