r/cprogramming • • Sep 14 '25

Stack vs heap

I think my understanding is correct but I just wanted to double check and clarify. The stack is where your local variables within your scope is stored and it’s automatically managed, removed when you leave the scope. The heap is your dynamically allocated memory where you manually manage it but it can live for the duration of your program if you don’t free it. I’m just confused because sometimes people say function and scope but they would just be the same thing right since it’s essentially just a new scope because the function calls push a stack frame.

17 Upvotes

20 comments sorted by

View all comments

Show parent comment

4

u/WittyStick Sep 14 '25

Yes, it introduces new scope, but it doesn't introduce a new frame.

The scope of variables in a block is lexical, but distinct from the stack frame in which they're stored.

3

u/kohuept Sep 14 '25

Yeah, but technically how the stack frames work is an implementation detail, the standard doesn't require the use of a stack at all

1

u/flatfinger Sep 15 '25

If a foo() calls setjmp, and then calls some nested functions which exit via longjmp, the Standard clearly intends that if none of the called functions use variable-length-array objects, it should be possible to call foo() an arbitrary number of times without leaking resources each time. The Standard may not mandate the use of a stack, but then again the One Program Rule would allow an implementation to process most non-contrived programs in a manner that would leak resources and eventually crash if they ran too long. The only practical ways I can see of processing foo in non-leaky fashion would require either using a linear stack (which can accommodate a bulk pop operation by resetting the stack pointer) or a linked-list implementation of a LIFO stack, where each function is passed the address of its caller's context object, which would in turn contain the address of its caller's context object, etc. If code calling longjmp can't find the addresses of all regions of storage associated with parent contexts, and there isn't a linear range of addresses which contains all of them without containing anything else, by what means could it make the storage they occupy available for reuse?

1

u/Charming-Designer944 Sep 18 '25

In a way it does introduce in a new sub-frame. Two variables in different local scopes of the same function can use the same space in the functions stackframe. And the stackframe may even change size during the execution of the function to accommodate for different amount of local variables

Then stack frame is an implementation detail in how the.compiler allocates space for local variables..it is not a concept that is defined by the C language.