Search code examples
c++visual-studiovisual-c++stack-overflow

How to determine the appropriate stack size for some program?


Noted that the default stack size from the compiler is 1MB and to increase the stack size, you have to manually enter the stack size in the linker>system configuration. Is there a way to see what is the stack size I need based on the code that I've written so I can manually enter the stack size without giving it too much?


Solution

  • In general you cannot know how much stack is needed before the program is executed. Consider this contrived example:

     void foo() {
         int x;  // on the stack
         std::cin >> x;
         if (x) foo();
         std::cout << x;
     }         
    

    In absence of optimizations that would transform the recursion into a loop, no matter how big your stack foo can exceed it or not depending on user input.

    In general it is not possible to decide beforehand how much stack is going to be used.