Talking about the difference between heap and stack

Source: Internet
Author: User
Tags stack pop

The author as a small white, for heaps and stacks of concepts, always feel very hazy, they know me, and I just occasionally see, and no Szse

In the computer field, however, stacks are a concept that cannot be overlooked, and stacks are two data structures. A stack is an ordered data structure of data items that can be inserted and deleted only at one end (called the top of the stack). In single-chip microcomputer applications, the stack is a special storage area, the main function is to temporarily store data and addresses, often used to protect breakpoints and the scene. Important: Heap, queue first, FIFO (Fifo-first in First out). Stack, advanced post-out (filo-first-in/last-out).

In general, if someone puts a stack together, it means stacks, not heaps ....

The difference between them, for beginners is always confused, the author himself is, so I think it is necessary to a little finishing, at least in his heart also has a concept. Ability problem, write bad, to this question, each it class of Bbs,blog have written very good, everybody can study. Baidu Encyclopedia on the heap and stack of the comparative analysis:

Stack space allocationStack (operating System): automatically allocated by the operating system to release, store the function parameter value, local variable value and so on. It operates in a manner similar to a stack in a data structure. Heap (operating system): Usually released by the programmer, if the programmer does not release, the end of the program may be recycled by the OS, distribution is similar to the listhow the stack is cachedThe stack uses a first-level cache, which is usually called when it is in storage, and is released immediately after the call. The heap is stored in a level two cache, and the life cycle is determined by the garbage collection algorithm of the virtual machine (it is not possible to be recycled once it becomes an orphan object). So the speed of calling these objects is relatively low.stack data structure differencesHeap (data structure): Heaps can be thought of as a tree, such as: heap sort. Stack (data structure): An advanced post-out data structure. For example: The class definition of the sequential stack Astack template < class T >class astack {private:int size;//The scale of the array T * STACKARRAY;//The array that holds the stack element int top; The subscript public:astack (int maxstacksize)//constructor {size = maxStackSize; stackarray = new T [maxstacksize] in the array element at the top of the stack; top = -1; }~astack () {delete [] stackarray;}//destructor bool Push (const t& Item); Pushes an element bool Pop (T & Item) into the top of the stack; POPs an element from the top of the stack bool Peek (T & Item) const; Access stack top element int IsEmpty (void) const {return top = =-1;} Detects if the stack is empty int isfull (void) const {return top?? size-1;} Check whether the stack is full void clear (void) {top?-1;}//Empty stack};


First, let's give an example:
void F () {int* p=new int[5];}
This short sentence contains the heap and stack, see new, we should first think that we have allocated a heap of memory, then the pointer p? He allocates a stack of memory, so the meaning of this sentence is: In the stack memory is stored in a pointer to a heap of memory p. The program will first determine the size of the memory allocated in the heap, then call operator new to allocate memory, and then return the first address of the memory, put in the stack, his assembly code under VC6 is as follows:
00401028 Push 14h
0040102A call operator new (00401060)
0040102F Add esp,4
00401032 mov dword ptr [Ebp-8],eax
00401035 mov eax,dword ptr [ebp-8]
00401038 mov dword ptr [Ebp-4],eax
Here, we do not release the memory for the sake of simplicity, then how to release it? Is it delete p? O, wrong, should be delete []p, this is to tell the compiler: I delete an array, VC6 will be based on the corresponding cookie information to do the work of releasing memory.
Well, let's go back to our topic: What's the difference between heaps and stacks? The author makes meanness summary to this end
The main differences are from the following points:
1, different management methods;
2, the space size is different;
3, can produce different fragments;
4, the growth direction is different;
5, the distribution method is different;
6, the allocation efficiency is different;
Management mode: For the stack, is automatically managed by the compiler, without our manual control, for the heap, the release of work by the programmer control, easy to produce memory leak.
Space size: Generally speaking, in 32-bit system, heap memory can reach 4G space, from this point of view heap memory is almost no limit. But for the stack, generally there is a certain amount of space, for example, under the VC6, the default stack space is 1M (as if it is not clear). Of course, we can modify:
Open the project and proceed to the following menu: Project->setting->link, select output in category, then set the maximum and commit of the stack in the reserve.
Note: The reserve minimum value of 4byte;commit is reserved in the virtual memory of the page file, it is set to a large size stack will open up a larger value, may increase the memory overhead and startup time.
Fragmentation problem: For the heap, frequent new/delete is bound to cause memory space discontinuity, resulting in a large number of fragments, so that program efficiency is reduced. For the stack, there is no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there will never be a memory block from the middle of the stack pop-up, before he pops up, in the back of his upper stack content has been ejected, detailed can refer to the data structure, here we are no longer one by one discussed.
Growth direction: For the heap, the direction of growth is upward, that is, to the memory address of the direction of increase, for the stack, its growth direction is downward, is to reduce the memory address direction of growth.
Allocation method: The heap is dynamically allocated and there are no statically allocated heaps. Stacks are allocated in 2 ways: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is assigned by the ALLOCA function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is released by the compiler without our manual implementation.
Allocation efficiency: The stack is the data structure provided by the machine system, the computer will support the stack at the bottom: allocate the address of the special register storage stack, the stack stack has a special instruction execution, which determines the efficiency of the stack is high. The heap is provided by C + + function library, its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for available enough space, if there is not enough space (possibly due to too much memory fragmentation), It is possible to invoke the system function to increase the memory space of the program data segment, so that there is a chance to divide the memory in sufficient size and then return. Obviously, the heap is much less efficient than the stack.
From here we can see that heap and stack, due to the use of a large number of new/delete, is prone to large amounts of memory fragmentation, because there is no dedicated system support, inefficient, due to the possibility of triggering user-state and nuclear mentality of the switch, memory applications, the cost becomes more expensive. So the stack is the most widely used in the program, even if the call of the function is done by the stack, the parameters in the function call, the return address, the EBP and the local variables are all stored in a stack. So, we recommend that you try to use stacks instead of heaps.
Although the stack has so many advantages, it is not so flexible compared to the heap, sometimes allocating a lot of memory space, or heap better.
Whether it is a heap or stack, to prevent the occurrence of cross-border phenomenon (unless you deliberately make it out of bounds), because the result of the cross-border is either a program crash, or destroy the program heap, stack structure, produce unexpected results, even in the course of your program, did not occur above the problem, you still have to be careful, Maybe when it's going to blow up, then debug is pretty hard:)

Talking about the difference between heap and stack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.