Recursive function causing an overflow despite it's not infinite

The following function I wrote causing the program to crash due to the stack overflow, although the recursion is finite.

public static void Key(char[] chars, int i, int l, string str) {
    string newStr=null;

    for(int j=0; j<l; j++)
        newStr+=chars[i/(int)Math.Pow(68, j)%68];

    if(newStr==str)
        return;

    Key(chars, ++i, l, newStr);
}

When I call the method with these parameters, all goes fine:

Key(chars, 0, 4, "aaaa");

But when it comes to bigger number of calls, it throws the StackOverflowException . So I assume the problem is that althogh the method is finite the call stack gets filled up before the the methods' job is done. So I have a few questions about that:

  • Why the functions don't get clear from the stack, they are no longer needed, they don't return any value.

  • And if so, is there a way i could clear the stack manually? I tried the StackTrace class but it's helpless in this case.


  • 1) The function clears when it has ended execution. Calling Key inside of itself means that every call to it will be on the stack until the last call ends, at which stage they will all end in reverse order.

    2) You can't clear the stack and carry on with the call.


    The stack is still limited. For standard C# applications it is 1 MB. For ASP it is 256 KB. If you need more stack space than that, you'll see the exception.

    If you create the thread yourself, you can adjust the stack size using this constructor.

    Alternatively, you can rewrite your algorithm so it keeps track of state without using recursion.


    它看起来像NewStr == Str的退出条件永远不会发生,最终,您将用完堆栈。

    链接地址: http://www.djcxy.com/p/80618.html

    上一篇: 堆栈溢出和递归序列表达式F#

    下一篇: 尽管不是无限的,递归函数会导致溢出