How is stack memory organized?
c
Solution
pps. In other words, is this the case, that each time, each function f(), f1(), and f2() get their "instance" of stack?
When a function is called it will allocate memory for the duration of the call. When the function returns, the memory is returned.
In your example, `f2()` will use the same instance of the stack as `f1()`, but since `f1()` has returned when `f2()` is called, the stack memory used by `f1()` is free to be re-used by `f2()`.
Stacks are allocated per thread, so in a multi-threaded program each thread will have its own stack.
Edit
It should be pointed out that the description above is how compilers usually implement local variables. The C standard does not specify that stacks need to be used, but it is the best solution (so far) for environments where an unknown amount of processes/threads need to share a limited amount of memory.
Edit 2
Dividing `f` into `f1` and `f2` is one way of reducing the stack memory consumption. Other ways are to allocate memory on the heap (with malloc/free) or statically (static allocation isn't thread-safe, so it reduces portability and reusability and should only be used as a last resort).
Say I had one local variable defined in f(), what would happen with it, when program entered inside f1()?
It would still be there. You can think of the stack as a pile of papers. Whenever you call a function, the caller adds a paper with the return address and space for the return value. The called function then adds another paper with the local variables. When a function returns, it removes the top paper (with its local variables) and jots down the return value on the next paper. The calling code reads the return value and removes the top paper, again exposing the paper with the caller's local variables.
Problem
I just want to make sure I get it right. Imagine the stack size for any program on my machine is 800 bytes (just example). Then, following code: ``` void f() { char x[300]; char y[300]; char z[300]; char t[300]; } ``` should overflow stack right (because 1200>800)? Now my question is, is the below approach an Ok way to defeat above mentioned stack overflow problem? ``` void f() { f1(); f2(); } ``` where: ``` void f1() { char x[300]; char y[300]; } void f2() { char z[300]; char t[300]; } ``` this way according to my reasoning each function consumes only 600 bytes (<800) of stack memory, so all should be OK. Am I right? ps. I am not referring to "other" data that could take up space on stack for the sake of this example. pps. In other words, is this the case, that each time, each function f(), f1(), and f2() get their "instance" of stack?