0
Can somebody please explain me what exactly is the stack and the heap on C++?
I don't really get this and would like to know what it means, I didn't understand the tutorial provided by the app.
2 Answers
+ 3
https://www.sololearn.com/discuss/567261/?ref=app
https://www.sololearn.com/discuss/604657/?ref=app
There are already plenty other posts about this topic, I would strongly recommend you using the search bar before posting a thread.
Often there will be somebody who already has asked the same or a similar thing.
+ 1
When hardware makers added an instruction to call a function that could return to the calling spot, they dedicated a register to the stack. The calling function would add storage for it's local variables plus for the arguments to the function about to be called (incrementing the register) and store copies of their values. The address to return to would also get added by the hardware. The new function would use that register with negative offsets to access the arguments. They would use positve offsets to access it's local variables. On return from a function, the register is put back to how it was. Therefore, the stack contains space for all local variables of all currently running functions plus return addresses on how to get back to continue the functions.
The heap is a section of memory reserved for allocation via new. Functions have a local or global variables that contains an address pointing to the heap allocated by new. That storage can then contain other pointers to more heap. It lives on until it is returned by the program or garbage collection hunts it down.