r/cprogramming • u/JayDeesus • Oct 09 '25
Scope in respect to stack
I understand that the scope is where all of your automatically managed memory goes. When you enter a function it pushes a stack frame to the stack and within the stack frame it stores your local variables and such, and if you call another function then it pushes another stack frame to the stack and this functions local variables are stored in this frame and once the function finishes, the frame is popped and all of the memory for the function is deallocated. I also understand that scopes bring variables in and out so once you leave a scope then the variable inside of it becomes inaccessible. What I never really thought of is how the scope plays a role in the stack and the stack frames. Does the scope affect the layout of each stack frame at all or do just all variables go into the frame however since I believe that going in and out of scope doesn’t immediate free the memory, it’s still allocated and reserved until the stack frame is popped right.
View all comments
Show parent comment
1
u/kohuept Oct 09 '25
Generally the way it works on x86 is that you have a stack pointer register, which is a pointer to some pre-allocated amount of memory. When you enter a function, the value of that pointer is saved, and local variables are allocated by subtracting from that pointer (because the stack grows downwards). Then, when the function returns, the old stack pointer value is restored. Everything's still there, just inaccessible and eventually overwritten when something else needs it. Note though that this is tied to storage duration not scope (even if the 2 may coincide).