Stack and stack differences

Source: Internet
Author: User

Preface:

InProgramDuring the design, the stack will always be exposed, and the difference between the stack and the stack, their respective roles during the running of the program, and how to use the stack to improve the running efficiency.

Many people do not know enough about it. Today, many GoogleArticleSo here is a complete summary, hoping to help you. I also hope to point out the shortcomings.

Stack is the space allocated when the function is called.

The space allocated on the stack is temporary. After the function exits, it will be released by the system and will not cause memory leakage. delete or free operations are not allowed, because the stack space is small, a large amount of memory blocks cannot be obtained on the stack.

Generally, less than 10 MB of heap memory is allocated in the unallocated space of the entire process. The memory is allocated by malloc or new and must be released by free or delete. A large amount of memory can be allocated on the stack, as long
Your machine eats away. In general, the memory allocated by new and malloc is on the heap, and the global variables are on the heap (but not new, the memory allocated by malloc is automatically cleared ). Function
Both its variables and constants are on the stack.

The C ++ memory pattern is generally divided:
Global data Zone
CodeZone
Stack Zone
Heap Area

Comparison Between Stack and stack

Compared with the functions and functions of stacks and stacks, stacks are mainly used to store objects and stacks are mainly used to execute processes.
This difference is mainly determined by the characteristics of the stack and stack:

InProgrammingFor example, in C/C ++, all method calls are performed through stacks, and all local variables and formal parameters are allocated memory space from stacks. In fact, it is not a allocation, but it can be used from the top of the stack,

Just like the conveyor belt in the factory, stack pointer will automatically guide you to the place where you put things. All you have to do is put things down. when exiting the function, you can modify the stack pointer

Content destruction mode is the fastest, of course, used to run the program. it should be noted that, during the allocation, for example, when assigning a data zone to a program module to be called, the size of the Data zone should be known in advance, that is

Although the allocation is performed when the program runs, the size of the allocation is fixed and remains unchanged. The "size" is determined during compilation, not during runtime.

Heap requests the operating system to allocate memory when the application is running. Because the memory allocated is managed by the operating system, it takes time to allocate and destroy the heap, therefore, the efficiency of using the heap is very low. however, the advantage of heap is that

The compiler does not need to know how much storage space to allocate from the heap, nor how long the stored data will stay in the heap. Therefore, storing data in a heap gives you more flexibility. In fact, object-oriented polymorphism, heap memory

Allocation is essential, because the storage space required by the polymorphism variable can be determined only after the object is created at run time. in C ++, when creating an object, you only need to use the new command to compile the relevant code. When executing the code

Data will be automatically stored in the heap. Of course, to achieve this flexibility, you will inevitably pay a certain price: It will take longer to allocate storage space in the heap! This is also the cause of low efficiency,

Difference between heap and stack (transfer)
I. prerequisites-program memory allocation
The memory occupied by a C/C ++ compiled program is divided into the following parts:
1. STACK: the stack is automatically allocated and released by the compiler, and stores function parameter values and local variable values.
. The operation method is similar to the stack in the data structure.
2. Heap-usually assigned and released by the programmer. If the programmer does not release the heap
OS recycle. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
3. The Global zone (static)-stores global variables and static variables, and initializes them.
The global variables and static variables are in the same region. uninitialized global variables and uninitialized static variables are in the adjacent
. -The system is released after the program ends.
4. Text Constant Area-constant strings are placed here. The program is released by the System
5. program code area-stores the binary code of the function body.
Ii. Example Program

// Main. cpp

 
Int A = 0; global initialization zone char * P1; Global uninitialized Zone Main () {int B; stack char s [] = "ABC"; stack char * P2; stack char * P3 = "123456"; 123456 \ 0 is in the constant zone, and P3 is in the stack. Static int C = 0; Global (static) initialization zone p1 = (char *) malloc (10); P2 = (char *) malloc (20 ); the allocated 10-byte and 20-byte areas are in the heap area. Strcpy (P1, "123456"); 123456 \ 0 is placed in the constant area, and the compiler may optimize it into a place with "123456" pointed to by P3 .}

Ii. Theoretical knowledge of heap and stack
2.1 Application Method
STACK:
Automatically assigned by the system. For example, declare a local variable int B in the function, and the system automatically opens up for B in the stack.
Space
Heap:
The programmer needs to apply and specify the size. In C, the malloc Function
For example, P1 = (char *) malloc (10 );
Use the new operator in C ++
For example, P2 = (char *) malloc (10 );
But note that P1 and P2 are in the stack.
2.2
System Response after application
STACK: as long as the remaining space of the stack is larger than the requested space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting the stack
Overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application

The linked list is traversed to find the heap node with the first space greater than the requested space, and then the node is linked from the idle node chain.

Delete the table and allocate the space of the node to the program. In addition, for most systems

In this way, the delete statement in the code can correctly release the memory.
Space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically
The remaining part is re-inserted into the idle linked list.
2.3 Application size limit
STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This sentence
The stack top address and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (
In other words, it is 1 m, which is a constant determined at the time of compilation.) If the applied space exceeds the remaining space of the stack
Overflow is displayed. Therefore, the space available from the stack is small.
Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses linked lists for storage.
The idle memory address is not consecutive, And the traversal direction of the linked list is from the low address to the high address. Heap
The size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and compared.
Large.
2.4 comparison of application efficiency:
The stack is automatically allocated by the system, which is faster. But programmers cannot control it.
The heap is the memory allocated by new, which is generally slow and prone to memory fragments. However, it is most convenient to use.
In addition, in windows, the best way is to use virtualalloc to allocate memory, which is neither heap nor stack.
Is to keep a fast memory directly in the address space of the process, although it is the most inconvenient to use. But it is fast and best
Active.
Storage content in 2.5 heap and stack
STACK: when calling a function, the first entry to the stack is the next instruction of the main function (the next instruction of the function call Statement ).
The address of the executable statement, and then the parameters of the function. In most C compilers, the parameters are from right to left.
And then the local variables in the function. Note that static variables are not included in the stack.
When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the last stack points to
Address, that is, the next instruction in the main function, where the program continues to run.
Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.
2.6 comparison of access efficiency
Char S1 [] = "aaaaaaaaaaaaa ";
Char * S2 = "bbbbbbbbbbbbbbbbb ";
Aaaaaaaaaaa is assigned a value at the runtime;
Bbbbbbbbbbbbb is determined during compilation;
However, in future access, the array on the stack is faster than the string pointed to by the pointer (such as the heap.
For example:

 # include 
void main ()
{< br> char A = 1 ;
char C [] = " 1234567890 " ;
char * P = " 1234567890 " ;
A = C [ 1 ];
A = P [ 1 ];
return ;< BR >}

Corresponding assembly code
10: A = C [1];
00401067 8A 4D F1 mov Cl, byte PTR [ebp-0Fh]
0040106a 88 4D FC mov byte PTR [ebp-4], Cl
11: A = P [1];
0040106d 8B 55 EC mov edX, dword ptr [ebp-14h]
00401070 8A 42 01 mov Al, byte PTR [edX + 1]
00401073 88 45 FC mov byte PTR [ebp-4], Al
The first type reads the elements in the string directly into the CL register, while the second type reads the pointer value first.
Reading characters in edX is obviously slow.
2.7 summary:
The difference between stack and stack can be seen in the following metaphor:
Using Stacks is like eating at a restaurant, just ordering (sending an application), paying, and eating (using ).
If you leave, you don't have to worry about the preparation work, such as cutting and washing dishes, and cleaning the tail work, such as washing dishes and flushing the pot. His advantage is that it is fast,
It is a low degree of freedom.
Using heap is like making your favorite dishes by yourself. It is troublesome, but it suits your taste.
High degree of Parallelism

 

For more information about the memory management and data structure when running the program, see the blog:

Underlying exploration-runtime Data Structure

 

 

If there is reprint please indicate the source: http://www.cnblogs.com/yanlingyin/

A fish @ blog

2011-12-10

Related Article

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.