Memory management-Heap and stack

Source: Internet
Author: User

Differences between stacks and heaps in program variable partitioning

(1) How to apply

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: Requires the programmer to apply himself and indicate the size of the malloc function in C, which is the new operator in C + +.

such as P1 = (char *) malloc (10); P1 = new CHAR[10];

such as P2 = (char *) malloc (10); P2 = new CHAR[20];

But note that P1, p2 itself is in the stack.

(2) Response of the system after application

Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.

Heap: First of all should know that the operating system has a record of the free memory address of the list, when the system receives the application of the program, it will traverse the list, look for the first space is larger than the requested space of the heap node, and then delete the node from the list of idle nodes, and the node's space allocated to the program. For most systems, the size of this allocation is recorded at the first address in the memory space, so that the DELETE statement in the code can properly free up the memory space. Because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.

(3) Size limit of application

Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.

Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.

(4) Comparison of application efficiency

The stack is automatically assigned by the system and is faster. But programmers can't control it.

The heap is the memory allocated by the malloc function, which is generally slower and prone to memory fragmentation, but it is most convenient to use.

(5) storage content in heaps and stacks

Stack: In a function call, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement), and then the parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that static variables are not in the stack. When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.

Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.

(6) Comparison of access efficiency

Char s1[] = "a";

char *s2 = "B";

A is assigned at run time;

and b is determined at compile time;

However, in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).

(7) Summary

The main differences between heaps and stacks are by 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 method:

For the stack, it is automatically managed by the compiler, without our manual control;

For heaps, the release work is controlled by the programmer and easily generates memory leak.

Space size:

In general, 32-bit systems, heap memory can reach 4G of 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. Of course, this value can be modified.

Fragmentation issues:

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 will be no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there is never a memory block from the middle of the stack pop, before he pops up, in the back of his upper stack content has been ejected, detailed reference data structure can be referenced.

Direction of growth:

For the heap, the direction of growth is upward, that is, toward the memory address increase direction;

For the stack, it grows in a downward direction, increasing in the direction of memory address reduction.

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 Malloca 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 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. Regardless of whether it is a heap or stack, avoid the occurrence of cross-border phenomena (unless you deliberately cross it), because the result of the cross-border is either a program crash, or destroy the program heap, stack structure, produce unexpected results.

Memory management-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.