Why C use stacks for storing the local variables? Is this just to have independent memory space or to have feature of automatic clearing of all the local variables and objects once it goes out of scope?
I have few more questions around the same,
Question 1) How local variables are referenced from the instruction part. Consider NewThreadFunc
is the function which is called by createThread function.
DWORD WINAPI NewThreadFunc(PVOID p_pParam)
{
int l_iLocalVar1 = 10;
int l_iLocalVar2 = 20;
int l_iSumLocalVar = l_iLocalVar1 + l_iLocalVar2;
}
The stack for this thread would look like this,
| p_pParam |
| NewThreadFunc()|
| 10 |
| 20 |
| 30 |
| |
.
.
.
Now my question is, while executing this function how would CPU know the address of local variables (l_iSumLocalVar
, l_iLocalVar1
and l_iLocalVar2
)? These variables are not the pointers that they store the address from where they have to fetch the value. My question is wrt the stack above.
Question 2) If this function further calls any other function how would the stack behave to it? As I know, the stack would get divided into itself further. If this is true how the local variables of the callee function gets hidden from the called function. Basically how the local variables maintains the scope rules?
I know these could be very basic questions but some how I could not think an answer to these.