First, the C Standard doesn't have anything to say about a runtime stack. Compilers are free to use any data structure they wish to implement the behavior of C. Some have used linked lists on a heap, and this is fine.
So just assume we have the more-or-less standard C implementation that puts return addresses, arguments, and local variables on a stack.
There is no algorithm (and therefore no person) that will always succeed in correctly predicting the stack size needed for an arbitrary computer program. This is a basic result of computer theory: a simple reduction from the halting problem.
However, you can impose rules on your programs that allow the max size stack to be predicted. In a nutshell, you disallow any form of recursion (including general recursion: A calls B calls C calls A), and you don't allocate variable-size data (e.g. with alloca()
or variable sized arrays) on the stack.
These kinds of rules are very common practice in safety-critical systems like pacemakers and flight controls. They can be checked by software tools, and such tools exist for safety critical system design, though they tend to be proprietary.
As @Jonathon Reinhart says, the procedure for establishing stack size is different for each OS.
Linux and Unix variants use the rlimit
and ulimit
scheme where stack size is a user resource constraint.
Windows associates a stack limit with each program. You can also get rlimit
-like control with Job Objects.
Conversely, I don't know if there is a Windows-like way to set a stack size limit in Linux executables, but would not be surprised to learn there is one.