Error StackOverflow

1
Hello, I would like to know why I get the StackOverflow error in this code, but if I add another condition in the recursive method, that is if (list.contains (numb)) I do not get this error.

(This code would be to check how many numbers exist in base 3 respecting the condition that from a digit d1 to a digit d2 there exists the relation | d2-d1 |

asked by anonymous 19.04.2015 / 00:52

1 answer

5

The answer is quite simple:

If you do not check if a given number already exists in your list, your code will continue to run recursively forever. And as recursive calls involve the creation of one more item in the call stack , one hour the memory in your system ends and gives the error quoted - literally translates as "overflow" of the stack.

How can you see this happening? Just debug the code (even if mentally):

  • The first time that recursive is called, the value of i is 1 (because it is at the beginning of the loop in main ), and so the value of numb will also be 1. >
  • This value is greater than 0 and less than 3, so okay, the process continues.
  • Ignoring other calls (to facilitate), eventually the execution will arrive at the call with numb+1 (which results in 2).
  • In this next call of recursive , the value of numb as 2 also goes through the simple checks (is greater than 0 and less than 3), then the process continues.
  • Ignoring the other calls (again, to facilitate), eventually the execution will arrive at the call with numb-1 (which returns to 1).
  • So it should be possible to realize that this form of implementation has everything going wrong and running forever (in loop ), unless you ignore calls to values that have already been processed ( which is just add to the condition you mention).

        
    19.04.2015 / 01:46