Вопрос

Lets say I have a c program where I use only stack variables, no dynamic variables (malloc, ...)

Is it possible to calculate how much memory my program will take during run time? and is it possible to change size of stack?

Это было полезно?

Решение

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.

Другие советы

On Linux, you can change the stack size limit with setrlimit(RLIMIT_STACK,...).

On Windows, the stack size is set at thread initialization time, via the dwStackSize parameter to CreateThread. To change it at compile time, you pass /F (Set Stack Size) to the compiler

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top