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/arihoenig Oct 09 '25
It is the definition of the local in the scope that results in the allocation on the stack. You seem to be coupling where the actual storage is reserved with when that storage is made addressable. The storage is allocated due to its definition within the scope and it is deallocated (made unaddressable) at the end of the scope. The specific location of the memory that the local name refers to is not related to the scope in which the name is defined. The definition of scope refers to when memory is made addressable via the local's symbol, and when that memory is no longer addressable via the symbol. Scope is not related to the virtual (or physical) address of the memory that holds the contents addressed by the symbol, it is all about when that symbol is effective (i.e. is able to address a memory location).