0

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;
}
8
  • 1
    if parent[i] is unsigned, this could be bad. Consider putting a breakpoint on the count = 1 condition to be sure. It'd be nice to know size too... Please add a runable example and make sure you have no warnings when compiling. Commented Apr 2, 2019 at 3:24
  • 14 is not an array, so what did you mean? Anyway, why do you use recursion there at all? Commented Apr 2, 2019 at 3:28
  • Please post the definition and data of the parent array. Also, I assume you mean level(i+1)? Commented Apr 2, 2019 at 3:29
  • Can you please give us more info on the error? Have you tried debugging to see what was the state of your program when it crashed? Can we see the parent array? The value of size? Afaik, instantiating 2 ints will overflow your stack with too much recursion. Commented Apr 2, 2019 at 3:30
  • @J.R. i never change, so it should be calling the same thing forever Commented Apr 2, 2019 at 3:30

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Did not find j, did you mean parent[i]?
@Deduplicator, j is the loop variable. You bring another valid point though. It could be parent[i].
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.