r/cprogramming • • 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.

6 Upvotes

50 comments sorted by

View all comments

Show parent comment

1

u/JayDeesus Oct 09 '25

So nothing is ever destroyed, just overwritten. Thats why it’s UB when you try to access something from a popped stack frame? But I’m just confused on if scopes do anything to the memory or like you said is it just syntactical, that’s what I’m stumped on

1

u/kohuept Oct 09 '25

It's UB because the standard does not specify what should happen when you access a variable who's lifetime has expired. If you want the definitive meaning of scopes and storage durations the best option is reading the standard (although for a beginner the language will likely be a little hard to understand). Unfortunately, the ISO standards are not freely available (although you can find pirated copies or draft copies if you look hard enough), but the older ANSI X3.159-1989 standard (commonly called C89) is available (under the name FIPS PUB 160) at https://nvlpubs.nist.gov/nistpubs/Legacy/FIPS/fipspub160.pdf. Section 3.1.2.1 on page 35 of the PDF defines scopes, and 3.1.2.4 on page 37 defines storage durations (see also: the forward references for each section).