C ++ Memory Management 3 (stack and heap)

Source: Internet
Author: User

Difference Between Stack and heap in program variable Partition

(1) Application Method
STACK: automatically assigned by the system. For example, declare a local variable int B in the function; the system automatically opens up space for B in the stack.
Heap: the programmer must apply for the heap and specify the size. In C, the malloc function is used, and in C ++, the new operator is used.
For example, P1 = (char *) malloc (10); P1 = new char [10];
For example, P2 = (char *) malloc (10); P2 = new char [20];
But note that P1 and P2 are in the stack.

(2) system response after application
STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting 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, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. For most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. Because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.

(3) Application size limit
STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. Because of this, 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 the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap 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 large.

(4) Comparison of Application Efficiency
The stack is automatically allocated by the system, which is faster. But programmers cannot control it.
Heap is the memory allocated by new. It is generally slow and prone to memory fragments, but it is most convenient to use.

(5) Storage content in heap and stack
STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by 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 stack points to the address of the initial storage, 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.

(6) Comparison of access efficiency
Char S1 [] = "";
Char * S2 = "B ";
A is assigned a value at runtime, while B is determined at 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:
Int main ()
{
Char A = 1;
Char C [] = "1234567890 ";
Char * P = "1234567890 ";
A = C [1];
A = P [1];
Return 0;
}
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 into EDX and then reads the characters according to edX, which is obviously slow.

(7) Summary
The main differences between stack and stack are as follows:
1. Different management methods;
2. Different space sizes;
3. Whether fragments can be generated is different;
4. Different Growth directions;
5. Different allocation methods;
6. Different Allocation Efficiency;
Management Method: For stacks, it is automatically managed by the compiler without manual control. For heaps, the release work is controlled by programmers and memory leak is easily generated.
Space size: Generally, in a 32-bit system, the heap memory can reach 4 GB. From this perspective, there is almost no limit on the heap memory. But for stacks, there is usually a certain amount of space. For example, under vc6, the default stack space is 1 MB. Of course, this value can be modified.
Fragmentation problem: for the heap, frequent New/delete operations will inevitably lead to memory space disconnections, resulting in a large number of fragments, reducing program efficiency. For the stack, this problem will not exist, because the stack is an advanced and outgoing queue. They are so one-to-one correspondence that it is impossible to have a memory block popped up from the middle of the stack, before the pop-up, the post-stack content on the stack has been popped up. For details, refer to the data structure.
Growth direction: For the stack, the growth direction is upward, that is, the direction to the memory address increase; For the stack, the growth direction is downward, is to increase towards memory address reduction.
Allocation Method: The heap is dynamically allocated without static allocation. There are two stack allocation methods: static allocation and dynamic allocation. Static allocation is completed by the compiler, such as local variable allocation. The dynamic allocation is implemented by the malloca function, but the dynamic allocation of stacks is different from that of stacks. The dynamic allocation is released by the compiler without manual implementation.
Allocation Efficiency: the stack is the data structure provided by the machine system, and the computer will provide support for the stack at the underlying layer: allocate a dedicated register to store the stack address, the output stack of the Pressure Stack has dedicated Command Execution, which determines the high efficiency of the stack. The heap is provided by the C/C ++ function library, and its mechanism is very complicated. For example, to allocate a piece of memory, library functions search for available space in heap memory based on certain algorithms (for specific algorithms, refer to data structures/operating systems, if there is not enough space (probably because there are too many memory fragments), it is possible to call the system function to increase the memory space of the program data segment, so that there is a chance to allocate enough memory, then return. Obviously, the heap efficiency is much lower than the stack efficiency.
From this point, we can see that compared with the stack, the use of a large number of new/delete operations may easily cause a large amount of memory fragments; because of the absence of dedicated system support, the efficiency is very low; because it may lead to switching between the user State and the core state, the memory application will become more expensive. Therefore, stacks are the most widely used in applications. Even function calls are completed using stacks. The parameters and return addresses in the function call process are as follows, both EBP and local variables are stored in stacks. Therefore, we recommend that you use stacks instead of stacks. Although the stack has so many advantages, but because it is not so flexible as the heap, sometimes it is better to allocate a large amount of memory space. Whether it is a heap or a stack, it is necessary to prevent cross-border phenomena (unless you intentionally cross-border it), because the cross-border result is either a program crash, or destroy the program's heap and stack structure to produce unexpected results.

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.