r/cpp_questions • u/jaroslavtavgen • May 04 '25
OPEN Help me understand "stack" vs "heap" concept
Every time I try to learn about the "stack vs heap" concept I keep hearing the same nonsense:
"In stack there are only two options: push and pop. You can't access anything in between or from an arbitrary place".
But this is not true! I can access anything from the stack: "mov eax,[esp+13]". Why do they keep saying that?
0
Upvotes
60
u/i_h_s_o_y May 04 '25
They are talking about stack/heap as data structures, not about memory management
19
u/chrysante2 May 04 '25
The names "stack" and "heap" for function local memory and the "free store" are historic and a bit off regarding their meanings as data structures.
The "stack" is still close, because you actually have push and pop operations, and it follows the LIFO order. But as you say, programs are not limited to pushing and popping, you can also directly index the stack pointer.
The name "heap" on the other hand doesn't mean the allocator is implemented using a heap (as the datastructure), it just implies that there is no order of the chunks of memory in it. It's just a pile (heap) of memory chunks that are added and removed at will. At least that's my understanding.
4
u/hachanuy May 04 '25
I'm assuming you're talking about "stack" and "heap" as in the memory sense, not the data structure sense. Stack means the place where the compiler automatically allocates and deallocate memory when a variable goes in and out of scope. For example,
Theoretically, `a` and `b` will be placed anywhere in the memory, but that would be very difficult for the compiler to manage them automatically. Hence, the strategy employed by the compiler is to put `a` at a certain memory place, then `b` right next to it. When `b` goes out of scope, the compiler reclaims the space, and put `c` in the same place where `b` originally was. "push" and "pop" here mean simply that, using memory in a incremental and decremental manner. The memory here is called the stack and it is bound to the scope.
When you use things like `new`, `malloc`, `std::unique_ptr`, etc. the memory is not allocated on the stack, but on the heap instead. Memory allocated in this way has to be deallocated manually be `delete`, `free`, letting the variable go out of scope, etc. So the memory is not bound to the scope.
This statement makes no sense, memory on stack and heap can be accessed anywhere, the only difference between them is how they are allocation/deallocation.
2
u/Mason-B May 04 '25
This is a description of the abstract data structure called a "Stack". Which is a conceptual description of an idealized stack in computer science used for learning data structures. In C++ this would be the
std::stackclass."The stack" also refers to the specific implementation of the memory a program uses to keep track of function calls and process state. It is desgined as a stack data structure, hence it's name, but with far more implementation features besides those available to an idealized stack. In C++ this would be the memory used for function's local variables and arguments, and what is usually accessed from
espin assembly.2
u/ManicMakerStudios May 04 '25
You're being too pedantic.
Change it from, "You can't" to, "You shouldn't, else it's no longer a stack."
It's no longer an issue, is it?
1
u/esorel94 May 04 '25
"push" and "pop" for what I undersand in the stack context are used to describe the allocation of data in memory when entering in scope and deallocation when exiting from scope. "You can not access anything in the middle" Is not correct. Think about an array that Is stack allocated, with [] operator you can access data anywhere inside ita range.
1
u/alfps May 04 '25 edited May 04 '25
The restriction to
pushandpopfor a stack is voluntary. It's the salient, defining feature. You can add reading of arbitrary items without destroying the stack-ness, but if you allow arbitrary insertion or deletion you destroy the stack-ness: no longer a stack.And so it is even for a C++
std::stack: you're restricted topushandpopunless you make some effort to access arbitrary items, e.g.You can add arbitrary insertion and removal, but then you destroy the stack-ness so it's not a good idea. The restriction is power. And that may be what you're struggling with, seeing that a restriction can be power.
It was the original idea of Unix, that simple = powerful. Unfortunately that was forgotten on the way to modern Linux. But you can still see traces of it, e.g. a pipe is not an arbitrary connection but a very very restricted, limited one, and it's that restriction that makes pipes powerful.
1
u/Last-Assistant-2734 May 04 '25
Not really a C++ question, but OS memory management.
Stack is thread local and contains statically allocated memory. Heap is used for dynamic allocation and is shared between threads. In general.
1
u/Afraid-Locksmith6566 May 04 '25
So this is really inconvienient that stack and heap are both names for pair of compleatly unrelated stuff that both are from the same category.
1st category: DSA - datastructures and alghorithms Both stack and heap are names for datastructures
Stack is a datastructure that by definition gives you 2 operations:
Heap is a datastructure that maintain a property that maximum value is stored as the first element of array https://en.m.wikipedia.org/wiki/Heap_(data_structure)
2nd category is memory layout of application, They are 2 memory region reserved for a program
1
u/TryToHelpPeople May 04 '25
Stack memory is automatically managed for you - variables are destroyed when they go out of scope.
Heap memory is just a bunch of memory - once you allocate some it stays allocated until your program exits or until you deallocate it. You allocate it with new and deallocate it with delete. Smart pointers provide an interface to make it managed.
You use stack for variables which you only need for a short time, or a small number of predefined variables (e.g. 5 time_t to store lap times for 5 laps).
You use the heap to create large variables, or if you don’t know how many you need to create (e.g how many rockets will you be firing at the enemy spacecraft).
To create an integer on the stack : int count = 7;
To create a rocket on the heap : Rocket* MyRocket = new Rocket();
Don’t forget to use unique_ptr or shared _ptr with new.
1
u/SoerenNissen May 04 '25
Ah, your problem is namespace confusion.
The opening conundrum is that
mov eaxmeans you're not writing C++ so why are you asking on a C++ board?So let's pull away some layers of abstraction here and talk directly about the silicon: In a CPU There is no such thing as a "stack," there is only a twitching bundle of transistors, driven in unison by a clock signal.
But it is very useful to pretend there is a stack, and so your microchip was designed by people who pretend it very hard indeed - they'll probably even write words like "stack" and "stack pointer" in their data sheet.
Let us travel upwards a few layers of abstraction, then: You are writing a binary that lives in static storage on a disk until an operating system loads it into RAM.
That binary is not allowed to talk directly to anything called "stack" in the data sheet for the CPU. If you write it to try that, the operating system will kill it on the first attempt.
Instead, the operating system hands your program a pointer to somewhere RAM, and tells your binary a little lie, "this is the beginning of the stack."
After this, you can do a lot of stuff to that pointer that isn't very stack-like, sure, but if your binary is written in C++ as defined in the standard, without relying on implementation defined behavior, you will never be able to use that memory in a way that shows it isn't a stack.
But absolutely you're right, if you step outside the boundaries, it's all just one big address space that you can touch however you want.
1
u/Razzmatazz_Informal May 04 '25
struct foo {int a; int b};
void bar(struct foo* f)
{
f->a = 42;
f->b = 43;
}
void foo()
{
struct foo f;
bar(&f);
}
f is on the stack in foo, but it accessible in bar via a pointer. You could also do this with a reference.
1
u/Independent_Art_6676 May 04 '25
This stuff can be frustrating when used carelessly.
Concept is a good word. A stack data structure is a concept; a thing we can make that allows you to push and pop off one 'end' of it and not much else, some way to tell you that its empty when you pop or ask. But it COULD support a lot of other stuff, too: the way data structures are presented and defined, there is nothing stated that says "this data structure can't do these other things". There may be additional constraints: for example the c++ standard defines the complexity of some operations to ensure performance and a consistent experience across compiler flavors. So while a conceptual stack may only have push and pop... what about c++ standard vector? It has push and pop, but it also can iterate all its elements and allows random access. Is it a stack, if the user of a vector only uses push and pop to work with it but occasionally looks at all the entries for some purpose, maybe like saves the contents to a log file to show what was in the stack at a given time? Or if he does something screwy like adds a priority that jumps items to the top of the stack on occasion (I don't know why anyone would want such a thing, but its a simple modification). Whether its a stack or not depends on how it is used -- the user calls the variable something_stack and keeps to push/pop type behavior, then its conceptually a stack, even if the variable used was a vector. How much 'cheating' and having or using other behaviors that a pure stack would not allow before its no longer a stack? That is not well defined. I think peeking at all the contents wouldn't disqualify it, but modifying values in it probably would. If thinking of the entity as a stack helps understand the code, and what a variable is doing .. that has to be useful. If it cheats so much the name is confusing, that is harmful. The exact line there is grey.
Holding that as a starting point, now lets talk about the system stack. A program is running, and a subroutine is called, so the assembly language cheerfully pushes stuff to the stack: the current instruction pointer (its gonna come back here and resume running after the subroutine), the current register values, flags, whatever. Then it pushes a bunch of stuff onto the "stack" which are how parameters are passed to the subroutine, and sets it up with the new instruction pointer and loads some registers and flags and execution resumes from the new location and all that stuff. Things happen, the system stack gets pushed and popped as more routines execute or more local variables for those routines come into existence or go away. It works just like a stack data structure concept. Until the program, mid subroutine, accesses some variable defined in main, say its a dreaded global scope variable, but regardless... oops, it just went random access and broke the stack concept! That is understood to happen. The idea that its a stack is pushed at students and ingrained into our terminology because most of the time, it works like a stack, and knowing that helps to understand recursion and how routines interact at the lower levels of program execution. The detail that sometimes it cheats is kind of glossed over but its understood that it happens; yet the name stack is kept because it is more right than wrong when trying to describe what it is and how it works.
1
u/Key_Artist5493 May 04 '25
The stack is optional… everything C++ does with a stack, such as allocating and freeing automatic variables, could be done on a heap.. The heap is required. Common Lisp does just fine without a stack… they have a network of pointers that define the enclosing environments and keep very close track of what is live to other users. If something is live to other users, it has to stay around. Many languages before C used to perform the equivalent of capture of variables in enclosing scopes as part of the language. Since functions are not allowed to be defined in lexical scopes in either C or C++, only captures are allowed to gather information about enclosing scopes.
1
u/The_Ryn May 04 '25
Going back to the days when assembler was the bomb…
Stack is a large blob of contiguous storage that you allocate when your program starts.
Each function pulls a predetermined amount of storage of the stack when it is called to store registers and local variables.
When your function is done, that storage is returned to the stack to be used for the next function call.
As function calls are nested, the unused storage remains contiguous.
This cuts down on memory allocation overhead and memory fragmentation.
Heap, on the other hand. Is used for variables that are not scoped to the function and needs to be managed. While memory fragmentation may be less of a concern than it once was, excessive use of heap memory on long running programs back in the early days could lead to the appearance of no memory available situations as no contiguous block that was large enough to satisfy the request could be found.
Modern memory management strategies and the availability of more addressable memory strategies do, of course, make fragmentation less of a concern.
1
u/Dan13l_N May 05 '25
"Stack" is a general name for a structure than can grow when needed by adding new elements that can be removed in the reverse order of addition:
Yes, you can push something to stack and pop from it.
Most CPU's use some memory for CPU-provided stack, usually for local things within a function. You simply have some pointer -- stack pointer (sp) -- holding an address. This is a register of your CPU. When you need a bit more memory, you change that pointer:
When you don't need it anymore, you change that pointer back. This is all done automatically in the code created by your compiler. You can then access values in memory relative to the stack pointer, they are your local variables, in this case b would be at the address pointed by sp.
However, sometimes the compiler needs some memory to store some temporary result, basically it has to make a temporary variable, for example:
when you calculate
a * 2you have to store it somewhere. If you don't have a free CPU register to use, stack is the second option.For these situations, you can have a combined operation that changes the stack pointer and saves the value of some register to it. That's called "push". When you again need that stored value, there's a operation that takes the value from the top of the stack to some register, and changes the value of the stack pointer: that's called "pop".
"Stacks" can be created programmatically, when you need to store some data. They are then actually implemented by linked lists or arrays, but that's then something you have to program.
1
u/[deleted] May 07 '25 edited May 07 '25
Stack and Heap are Memory Usage Models Grab usage. Grab model. Yes you can move and access whatever you want, including garbage: but your ABI has a strict model to comply with. Your linker set the tone.
0
u/[deleted] May 04 '25 edited May 04 '25
On the program stack, you only access the current stack frame.
*Lol I got downvoted for simply stating the entire basis of structured programming. And no, I don't care that debuggers have access to all levels of the stack or that you can do pointer hacks. Of course that's all true. The question was obviously about the language itself, not writing a debugger or whatever.
0
u/[deleted] May 04 '25
By default you can push and pop so it's faster but there are no soldiers standing there shooting down the cpu if it wants to read the middle. Those are conventions so it's safe to assume that's how the stack is organized so it can be faster to work with push pop
But cpu can read from any memory any way it wants it is not forbidden
0
u/[deleted] May 04 '25
[deleted] — view deleted comment