Analysis on the difference of memory allocation between stack area and heap area

Source: Internet
Author: User

The following is a detailed analysis of the differences between the stack area and the heap area memory allocation, the need for friends can come to the reference

has always been the understanding of this problem is hazy, I believe a lot of friends are also like this, always hear the memory will be allocated on the stack, one will be allocated on the heap, then what is the difference between them? To illustrate the problem, let's take a look at the internal memory of the organization.

As you know, the memory that the program occupies is divided into the following parts.

1. Stack area (stack)
The compiler automatically assigns the release, the value of the stored function, the value of the local variable, and so on, the allocation of memory is continuous, similar to what we call the stack, if it is not clear, then put it to a group, its memory allocation is continuous allocation, that is, the allocated memory is within a contiguous memory area. When we declare a variable, the compiler automatically allocates memory to the end of the current stack.

2, heap area (heap)
Usually released by the programmer, if the programmer does not release, the program ends may be recycled by the operating system. Similar to linked lists, in-memory distributions are not contiguous, they are blocks of memory in different regions that are linked by pointers. Once a node is disconnected from the chain, we have to artificially release the severed node from memory.

3. Global zone (static zone)
The storage of global variables and static variables is placed in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another contiguous area. Released by the system after the program is finished

4. Text constant Area
The constant string is put here. Released by the system after the program is finished

5. Program code Area
Binary code that holds the body of the function.

Let's look at an example first.
char c; Allocate on stack
Char *p = new CHAR[3]; Allocated on the heap, assigning the address to P;

When the compiler encounters the first instruction, calculates its size, and then goes to find the current stack of space is greater than the amount of space required to allocate, if the stack space is larger than the requested space, then allocate memory space for it, note: here, the space within the allocation is continuous, and then the last allocation after the end of the allocation. If the amount of space within the stack is less than the requested space, then the system will reveal the stack overflow and give the corresponding exception information.

When the compiler encounters the second instruction, because P is allocated on the stack, the same method is allocated for p in space and above, but when the new keyword is encountered, the compiler knows that this is the dynamic memory space that the user requested, so it goes to the heap to find the space allocation. Note: The memory space on the heap is not contiguous, it is connected by the corresponding linked list of the inner chunk when the space area, so after the allocation of memory space is assigned, it will not immediately allocate the corresponding space, but first to calculate the required space, and then to the entire heap (that is, across the chain of nodes), Allocates the memory block that was encountered for the first time to it. Finally, the first address of the array of characters allocated on the heap is assigned to p. At this time, it is clear that P is now storing the first address of the character array requested in the heap, that is, the address of the array requested in the heap is now assigned to the pointer variable p applied on the stack. To illustrate the problem more visually, see:

As you can see, the first address of the dynamically allocated array on the heap is stored in the content pointed to by the pointer p.

Note : The memory space requested on the stack, when we are out of the scope of the variable, the system will automatically reclaim the space, and the space requested on the heap, when the corresponding scope, we need to explicitly call Delete to free the requested memory space, If we do not release these spaces in time, memory fragmentation becomes more and more, and our actual memory space becomes less and more, i.e., more and more isolated blocks of memory. Here, we know that the memory area of the heap is not contiguous, or the effective memory area through the linked list pointers, if we apply to a piece of memory, then this piece of memory will be from a continuous (linked table connected) memory block, if we are exhausted, we do not release it in time , then it will be isolated, because there is no pointer to it, so this area will become memory fragmentation, so after the use of dynamically allocated memory (through the new application), it is important to explicitly delete it. For this, be sure to remember ...

The above for you to state the concept between them, for their use of comparison, here I can not be interrupted, for this issue, online a netizen's article elaborated in more detail, and with the professional color, the following article is part of the piece.


Limit for size 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.

Comparison of application efficiency:
The stack is automatically assigned by the system and is faster. But programmers can't control it.

Heap is the memory allocated by new, the general speed is relatively slow, and prone to memory fragmentation, but the most convenient to use.

In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, nor in the stack is directly in the process's address space to keep a fast memory, although the most inconvenient to use. But the speed is fast, also the most flexible.
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.

Comparison of access efficiency
Char s1[] = "AAAAAAAAAAAAAAA";
Char *s2 = "BBBBBBBBBBBBBBBBB";

AAAAAAAAAAA is assigned at run time;
And BBBBBBBBBBB 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).

Like what:

1 voidMain ()2 {3CharA =1;4CharC[] ="1234567890";5Char*p ="1234567890";6A = c[1];7A = p[1];8return;9}

The corresponding assembly code

1 Ten: a = c[1];2 004010678A 4D F1 mov cl,bytePTR [ebp-0Fh]30040106A the4D FC movbytePTR [ebp-4],CL4  One: a = p[1];50040106D 8B -EC mov edx,dword ptr [ebp-14h]6 004010708A the  onmov al,bytePTR [edx+1]7 00401073  the  $FC movbytePTR [ebp-4],al

The first reads the elements in the string directly into the register CL, while the second one reads the pointer values into EDX, which is obviously slow to read the characters according to EdX.

Summary:
The difference between heap and stack can be seen in the following analogy:
Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.

Using the heap is like making your own favorite dishes, more troublesome, but more in line with their own tastes, and freedom

Transferred from: http://www.jb51.net/article/40513.htm

Analysis on the difference of memory allocation between stack area and heap area

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.