Groothi
Groothi

Reputation: 1

Stack OverFlow with Recursion

There is a stack overflow from my code I do not really know what is causing it. Parent is a fixed array like 14.

protected:
int* parent = new int[14];
int size = 14;

int Tree::level(int i) {
  int count = 0;

  for (int j = 0; j < size; j++) {
    if (parent[i] == -1) {
        count = 1;
    } else {
        count = level(i) + 1; //this is causing the stack Overlow
    }
  }
  return count;
}

Upvotes: 0

Views: 147

Answers (2)

R Sahu
R Sahu

Reputation: 206577

The recursive call in the following call is bound to cause an infinite recursion since i is not changed in the function.

count = level(i) + 1;

I am guessing that you meant to use j or parent[i] instead of i in that call. It's hard to tell what is the right value to use in the recursive call without more context.

Upvotes: 4

TruthSeeker
TruthSeeker

Reputation: 1579

In case of condition parent[i] == -1 false, function "level" becomes infinite recursive and hence stack overflow.

Upvotes: 0

Related Questions