0

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?

MomoVR
  • 113
  • 1
  • 8
  • 3
    You shouldn't use recursion for this problem. Look into [converting recursive algorithms to loops](https://stackoverflow.com/questions/159590/way-to-go-from-recursion-to-iteration). – Kirk Woll Jan 28 '22 at 16:18
  • Where specifically is the exception thrown? A stack trace would be useful. – John Glenn Jan 28 '22 at 16:21
  • @JohnGlenn The stack trace is going to be 430 calls deep lol – Nigel Jan 28 '22 at 16:22
  • Heh heh... yes, but having to copy the whole thing may be an enlightening experience. Was that a mean question? :) – John Glenn Jan 28 '22 at 16:24
  • 1
    There is too much code in these methods. There is also too much code duplication. Split up into smaller methods, and create more methods to remove code duplication. – Bent Tranberg Jan 28 '22 at 16:25
  • Haha yes, it is just a style of coding. Don't really like it when there are much methods in my code. But i'm gonna clean it up a bit more and use more methods. – MomoVR Jan 28 '22 at 18:03
  • @MomoVR Like it or not, more methods is easier to maintain, and makes the bite-sized chunks often re-useable. Plus it will keep you away from DRY violations, which are the ultimate symptom of bad code. Save yourself time now and learn to code effectively while you are still a beginner. – Nigel Jan 28 '22 at 19:25

1 Answers1

3

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);
}
Nigel
  • 2,961
  • 1
  • 14
  • 32