Stack Memory vs Heap Memory

Steveng picture Steveng · Apr 29, 2011 · Viewed 134k times · Source

Possible Duplicate:
What and where are the stack and heap

I am programming in C++ and I am always wondering what exactly is stack memory vs heap memory. All I know is when I call new, I would get memory from heap. If if create local variables, I would get memory from stack. After some research on internet, the most common answer is stack memory is temporary and heap memory is permanent.

Is stack and heap memory model a concept of operating system or computer architecture? So some of it might not follow stack and heap memory model or all of them follow it?

Stack and heap memory is the abstraction over the memory model of the virtual memory ( which might swap memory between disk and RAM). So both stack and heap memory physically might be RAM or the disk? Then what is the reason where heap allocation seems to be slower than the stack counterpart?

Also, the main program would be run in the stack or a heap?

Also, what would happen if a process run out of the stack memory or heap memory allocated?

Thanks

Answer

Eoin picture Eoin · Apr 29, 2011

In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.

The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)

The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.

Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.

Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.