Home > Software design >  Segmentation fault in static member function c
Segmentation fault in static member function c

Time:02-17

class Adder {
public:
    static int Solve(int a, int b) {return a   b;}
};

class Substructor {
public:
    static int Solve(int a, int b) {return a - b;}
};

class Comparer {
public:
    static bool Solve(int a, int b) {return a < b;}
};

class If {
public:
    static int Solve(bool term, int a, int b) {return term ? a : b;}
};

class Fibo {
public:
    static int Solve(int num) {
      int res =
      If::Solve(
        Comparer::Solve(num, 2),
        1,       
        Adder::Solve(
          Fibo::Solve(Substructor::Solve(num, 1)),
          Fibo::Solve(Substructor::Solve(num, 2))
        )
        
      );
      return res;
    }
};

int calc(int x) {
  return Fibo::Solve(x);
}

#include <iostream>
int main() {
  std::cout << calc(5) << '\n';
  return 0;
}

This code leads to segmentation fault. I tested all classes separately, write recursive fibo static member function without other static member functions and it works. While combined it crushes. How to fix it and why it crush ?

CodePudding user response:

The problem arises here:

class Fibo {
public:
    static int Solve(int num) {
      int res =
      If::Solve(
        Comparer::Solve(num, 2),
        1,       
        Adder::Solve(
          Fibo::Solve(Substructor::Solve(num, 1)),
          Fibo::Solve(Substructor::Solve(num, 2))
        )
      );
      return res;
    }
};

In the If::Solve() sentence, what you expected maybe, if Comparer::Solve(num, 2) checks that num<2, return 1 and do not evaluate the remaining expressions Fibo::Solve(Substructor::Solve(num, 1)) and the second one, it will not work as you expected. To evaluate If::Solve(), every arguments must be evaluated before to pass to If::Solve(). As it evaluates again and again recursively, stack overflow occurs, therefore program terminates. If you really wish to make it run, modify like this:

class Fibo {
public:
    static int Solve(int num) {
        if (Comparer::Solve(num, 3)) {
            return 1;
        }
        else return Adder::Solve(
            Fibo::Solve(Substructor::Solve(num, 1)),
            Fibo::Solve(Substructor::Solve(num, 2))
        );
    }
};

This guarantees that if num is 1 or 2, return 1 and does not evaluates remaining expressions.

  • Related