Segmentation Fault on Recursion

233 views Asked by At

I want to count the number of recursivily call that has a number in the Collatz Sequence. But for such a bigger number for example 4565458458

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int f(int value){
    if(value==1) return 1;
    else if(value%2 == 0) return value/2;
    else return 3*value+1;
}

int g(int value){
   if(value == 0) return 0;
   if (f(value)==1) return 1;
   return 1 + g(f(value));
}

int main(int argc, char *argv[]){
    int nSteps=0;
    istringstream iss(argv[1]);
    int;
    if(!(iss >> num).fail()){
        if(num < 0) cout << "0" << endl;
        else{
            nSteps = g(num);
            cout << "Result: " << nSteps << endl;
        } 
    }
    else{
        cout << "Incorrect line paramaters: ./g n" << endl;
    }
    return 0;
}
1

There are 1 answers

1
Hans Olsson On

Your program will use a lot of stack-memory for large inputs.

In addition f should have the same input and output type (originally it had "unsigned long long" as input and int as output), or the result will be wrong.

I would advise you to first rewrite g without recursion, and if that works try to investigate how to get g to be efficient with tail-recursion (the current variant does probably not support it).

Using a debugger as others suggested is also good, especially if it crashes before calling 'g'.

Finally 'num<0' does not make sense for an unsigned 'num'.