0

My textbook says that following:

Once the operating system decides to create a new process, it allocates space for all elements of the process image; therefore, the OS must know how much space is needed for the private user address space (programs and data) and the user stack.

As I understand it, the stack contains functions and local variables. And since much of the input into functions and the data resulting from any associated computations cannot be known at compile-time, the OS must allocate a static amount of memory to serve as the stack.

Given this, how does the OS determine at compile-time the sufficient amount of memory required by constituents of the stack? Given the dramatic variability of programs, I cannot imagine how the OS achieves this task. It would seem that if one tried to allocate a fixed amount of memory as the stack at compile-time, it would regularly result in either too much or too little memory. However, I presume that there is an effective mechanism in place to deal with this (to allocate an appropriate amount of memory as the stack); otherwise, stack overflows would be a common occurrence.

I would greatly appreciate it if someone could please take the time to clarify this concept.

handler's handle
  • 375
  • 1
  • 2
  • 10
  • *The compiler determines the stack size and layout using quite complex optimization algorithms.* http://stackoverflow.com/questions/21021223/how-does-the-gcc-determine-stack-size-the-function-based-on-c-will-use – handler's handle Jan 30 '17 at 11:08

2 Answers2

1

I think you have never heard of stack overflow.

The short answer is that it cannot determine at compile time. Because if it was possible to calculate the amount of stack memory required at compile-time, there would be no such thing as stack overflow occuring as the compiler would simply give an error telling that the amount of stack memory required exceeds the limit.

Consider the simple function:

int foo() 
{
     return foo();
}

the function will compile successfully. But will result in stack overflow.

Sumeet
  • 8,086
  • 3
  • 25
  • 45
  • *The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory.* This clarified my understanding. Thanks. – handler's handle Jan 30 '17 at 10:54
1

The stack size is normally determined by the linker. Most linkers have options for setting the stack size. The stack is then created by the program loader along with the rest of the program's address space as it reads the instructions from the executable file.

user3344003
  • 20,574
  • 3
  • 26
  • 62