Search code examples
c#stack-overflow

Stack Overflow after too many non-recursive Method Calls


I'm currently writing a console program that's split into many different tasks/methods. It roughly goes like this:

static void method1() {
    //do something
    method2();
}

static void method2() {
    //do something
    method3();
}

......

static void methodN() {
    //doesn't get executed because there's a StackOverflow
}

My question is, does this lead to a StackOverflow eventually? There is no recursion and no infinite loop, just that every method runs the next method at the end to keep the program going.

If this is the reason why I get a StackOverflow, what can I change to prevent this?

Thanks in advance!


Solution

  • If you keep calling methods like that, there will eventually be a stack overflow. Exactly when depends on how big your stack is. According to this post, it's 1MB.

    To avoid stack overflows, have the methods return before calling the next one. According to what you said, you have divided up your program into methods:

    static void Method1() { ... }
    static void Method2() { ... }
    static void Method3() { ... }
    static void Method4() { ... }
    

    Instead of calling method2 from inside method1 and calling method3 from inside method2, you can call all these methods sequentially in your Main method:

    public static void Main(string[] args) {
        Method1();
        Method2();
        Method3();
        Method4();
    }
    

    This way you won't fill up the stack.

    Just for fun, I wrote this little piece of code to find out when will Stack Overflow occur:

    public static void Main(string[] args) {
        Method(1, 1);
    }
    
    static void Method(int x, int y) {
        Console.WriteLine(x);
        Method(x + 1, y + 1);
    }
    

    For me, it shows 173897 before saying a stack overflow occurred.