0

I have a code that calls itself (java) ..when it does not get some values.

public void recfunction() {
    ---do something----
    if not found a then
    call recFunction();
    if found a save a and then exit the function.
}

recfunction can be called at most 5 times within itself. I get the value of "a" within 5 times. Will I get a StackOverflowError if I run this function 1000 times.

Edit: What I am trying to ask is when the function exits...will the Stack frames for all the calls be removed.

Mallik Kumar
  • 540
  • 1
  • 5
  • 28

3 Answers3

0

you can try it and find out, but no, as long as it is executing actual code and stays within stack limits it will not. stack size in java is 400k so as long as you're not tracking tons of varas on each call you should be fine.

If it only runs 5 times before throwing a stackoverflowerror, it's because you exceeded your stack.

Eric
  • 946
  • 2
  • 12
  • 25
0

The specific answer to your question is, "it depends."

But in general, yes, a recursive function that runs amok can cause a stack overflow error.

Particularly in Java, you have some control of stack size. So you can start the JVM with a smaller or larger stack, which will obviously impact how much stack there is to overflow.

Also, the amount of local storage you allocate in the function will contribute. If your function doesn't use any stack at all - just calls itself and maybe decrements a counter - you will have to use up the stack with only return address pointers and basic stack frame data.

But if you allocate a 1000-element array of objects in each local stack frame, then obviously you will consume more stack "per call", and thus you can overflow the stack in fewer levels of recursion.

aghast
  • 14,785
  • 3
  • 24
  • 56
0

Firstly, that code clearly won't compile, let alone run...

Secondly, assuming it did compile you could compile it and run it.

Most importantly, if you were to run it on multiple configurations you would discover different answers. See this question for example:

java -Xss4m Test

This will increase the stack size to four megabytes.

Community
  • 1
  • 1
autistic
  • 1
  • 3
  • 35
  • 80