In C ++, stack memory contains local variables that are stored / created. The stack is also used to store parameters passed to functions.
The stack is similar to the std :: stack class, you push the parameters on it, and then call the function. Then the function knows what parameters it expects, can be found at the end of the stack. Similarly, a function can push local residents to the stack and pop out of it before returning from the function. (optimization of the caveat compiler and calling conventions - all this is not so simple)
The stack is best understood from a low level, and I would recommend this link Art of Assembly - Passing parameters on the stack . It’s rare if someday you will consider some kind of manual stack manipulation from C ++.
In general, a stack is preferable because it is usually located in the CPU cache, so operations with objects stored on it tend to be faster. However, the stack is a limited resource and should not be used for anything large. Running from stack memory is called stack buffer overflow . This is a serious thing to come across, but you really shouldn't run into it unless you have a crazy recursive function or something like that.
Heap memory is very important, as rskar says. Generally speaking, C ++ objects allocated by the new, or memory blocks allocated using malloc, fall into the heap. Heap memory should almost always be freed manually, although you should use a smart pointer class or similar to avoid having to keep that in mind. Running from heap memory can (will?) Result in std :: bad_alloc.
Eoin Apr 29 '11 at 19:34 2011-04-29 19:34
source share