stack(栈) and heap(堆)

Heap is a large pool of memory used for dynamic allocation. When using new operator, to allocate the memory, the memory is assigned from heap. When a dynamically allocated variable is deleted, the memory is “returned” to the heap and can then be reassigned as future allocation requests are received.

The heap has advantages and disadvantages:
1) Allocated memory stays allocated until it is specifically deallocated (beware memory leaks).
2) Dynamically allocated memory must be accessed through a pointer.
3) Because the heap is a big pool of memory, large arrays, structures, or classes should be allocated here.

As a structure, stack has a last-in, first-out (LIFO) property. The call stack is a fixed-size chunk of sequential memory addresses. The stack pointer keeps track of where the top of the stack currently is. Parameters, local variables, and function calls are pushed on stack.

The stack has advantages and disadvantages:

1) Memory allocated on the stack stays in scope as long as it is on the stack. It is destroyed when it is popped off the stack.
2) All memory allocated on the stack is known at compile time. Consequently, this memory can be accessed directly through a variable.
3) Because the stack is relatively small, it is generally not a good idea to do anything that eats up lots of stack space. This includes allocating large arrays, structures, and classes, as well as heavy recursion.

reference: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

原文地址:https://www.cnblogs.com/xispace/p/3393386.html