What id stack? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What id stack?

memory

27th Oct 2017, 8:44 AM
Sohel Rauf Sayyad
Sohel Rauf Sayyad - avatar
5 Answers
+ 3
You mean what IS stack? If so, then stack is a data structure, that allows two operations: push and pop. Push - puts an item on top of the stack, and pop - gets the top item from the stack. It is very common in programming and computer architecture. You may often encounter people talking about some variable being placed in the stack. To understand that, you'll need to understand how function calls are implemented. That's a bit longer topic, than I'm willing to write about right now, but in a nutshell, all the local function variables as well as it's parameters are placed on the 'stack frame' of that function. That stack frame gets automatically deleted upon the function return. Contrary to that, there is a 'heap' aka 'dynamic memory', where space is allocated with operator new, and deleted with operator delete. Example: int main() { int a; // a is on the stack int b = new int; // b is on the heap delete b; // we should always delete dynamic variables } // a gets deleted from the stack automatically here
27th Oct 2017, 10:27 AM
deFault
+ 1
@Vincent Blankfield Variables may be placed in registers instead, they don't have to be on the stack for function calls
27th Oct 2017, 10:40 AM
aklex
aklex - avatar
+ 1
@0xDEADBEEF, Really? I specifically wrote this: "That's a bit longer topic, than I'm willing to write about right now, but in a nutshel...". The main point was about stack/heap as in auto vs manual memory management.
27th Oct 2017, 10:47 AM
deFault
+ 1
But you also said " all the local function variables as well as it's parameters are placed on the 'stack frame' of that function."... Consider it as me adding a small detail :)
27th Oct 2017, 11:03 AM
aklex
aklex - avatar
+ 1
@0xDEADBEEF, Sure. There are many more details to add. Like global variables, call conventions, literals... Also there are a lot of architectures, some of them may not even have general purpose registers (I'm not sure if there exists a real example of such architecture, with c++ compiler for it :) Still, to be able to use a language like C++ effectively, a programmer needs to have a clue about stack vs heap memory. I tried to give an extremely superficial explanation of the topic. And as for the local variables being placed in the registers, imo this nuance is a bit more advanced, and a bit less important.
27th Oct 2017, 11:26 AM
deFault