Search code examples
c#recursionstack-overflow

StackOverflowException in recursive interpreter written in C#


I'm trying to create a simple interpreter in C#.

Sadly it can only run ~1000 lines of code, because of a System.StackOverflowException.

void InterpretLine(int lineIndex, string[] lines)
{
    // Do interpreter stuff

    InterpretLine(lineIndex + 1, lines);
}

I can't seem to prevent or to catch the error. How can I fix this?


Solution

  • You are going to have to change your logic to not use recursion for reading each line. If you use recursion you will add a new function call to the stack for every layer of recursion, and the prior function calls will not be removed until the exit condition is met. If you make it 500 or so calls deep you can expect a stackoverflow exception.

    Now, I don't have time to read over your code, but I can tell you what you need to do: Turn your recursive call into a loop.

    Your code can probably be broken down into something like this:

    void ExecuteProgramLine(int lineNumber)
    {
       InterpretAndRunLine(lineNumber);
       ExecuteProgramLine(lineNumber + 1);
    }
    

    You will want to convert that to this:

    for(int lineNumber = 0; lineNumber < fileLines) // (foreach loop is probably better)
    {
        InterpretAndRunLine(lineNumber);
    }