On the difference between stack area and heap area memory allocation _c language

Source: Internet
Author: User
Tags data structures
has always been the understanding of this problem is more hazy, I believe many friends are also like this, always hear the memory will be allocated on the stack, and then in the heap allocation, then what is the difference between them? To illustrate this issue, let's take a look at the organization inside the memory.



The above diagram shows that the memory occupied by the program is divided into the following parts.

1, stack area (stacks)
The compiler automatically assigns the release, storing the parameter values of the function, the value of local variables, and so on, the allocation of memory is continuous, similar to what we call the stack, if it is not clear, then think of it as a number of groups, its memory allocation is continuously allocated, that is, the allocated memory is in a contiguous area of memory. When we declare a variable, the compiler automatically allocates the memory at the end of the current stack area.

2. Heap area (heap)
Typically released by programmers, if programmers do not release, the program may end up being recycled by the operating system. Similar to linked lists, the distributions in memory are not contiguous, and they are the memory blocks of different regions linked by pointers. Once a node is disconnected from the chain, we have to artificially release the disconnected node from memory.

3, Global zone (static area)
The storage of global variables and static variables is put together, initializing global and static variables in an area, uninitialized global variables and uninitialized static variables in another contiguous area. Released by system after program is finished

4. Literal constant Area
The constant string is here. Released by system after program is finished

5. Program code Area
The binary code that holds the body of the function.

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

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

When the compiler encounters the second instruction, since p is allocated on the stack, it is the same as the above method in allocating space for P, but when the new keyword is encountered, the compiler knows that this is the dynamic memory space that the user is requesting, so it will go to the heap to find the space allocation. Note: The memory space on the heap is not continuous, it is by the corresponding linked list of its space area when the inner block connection, so after assigning the allocated memory space, it will not immediately allocate the appropriate space, but first to calculate the required space, and then to the entire stack (that is, the entire chain of nodes), Allocate the first memory block you encounter to it. Finally, the first address of the array of characters allocated on the heap is assigned to p. At this point, it is clear that P now holds the first address of the array of characters applied in the heap, that is, the address of the array of applications in the heap is now assigned to the pointer variable p applied on the stack. For a more descriptive question, please look at the following image:



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

Note: The memory space requested on the stack, when we have the scope of the variable, the system will automatically reclaim the space, and on the heap, when the corresponding scope is out, we need to explicitly call Delete to free the requested memory space. If we do not release these spaces in time, there will be more and more memory fragments in memory, so that our actual memory space will become less and more, that is, more and more isolated chunks of memory. Here, we know that the memory area in the heap is not contiguous, or that a valid memory region is connected by a linked list pointer, if we apply for a piece of memory, then this chunk of memory will be disconnected from the contiguous block of memory that is connected through the linked list, and if we do not release it in time after use , then it will be isolated, because there is no pointer to it, so this area will become a memory fragment, so after the use of dynamically allocated memory (through the new request), be sure to explicitly delete it. For this, be sure to remember ...

Above to give you a statement of the concept between them, for their use of comparison, here I can not be intermittent statement, for this problem, online a netizen's article elaborated in more detail, but with a professional color, the following article is part of the piece.


Size limit of request
Stacks: In Windows, stacks are data structures that extend to a low address and are a contiguous area of memory. The address of the top of the stack and the maximum capacity of the stack are predetermined by the system, in Windows, the size of the stack is 2M (also some say 1M, in short, a compile-time constant), if the application space over the stack of remaining space, will prompt overflow. Therefore, the space can be obtained from the stack is small.

Heap: The heap is a data structure that is extended to a high address and is a contiguous area of memory. This is because the system is used to store the free memory address of the list, nature is discontinuous, and the link list of the traversal direction is from the low address to the high address. The size of the heap is limited by the virtual memory available in the computer system. This shows that the heap to obtain a more flexible space, but also relatively large.

Comparison of application efficiency:
The stack is automatically allocated by the system, faster. But programmers are out of control.

A heap is a memory that is allocated by new, typically slower, and prone to memory fragmentation, but is most convenient to use.

In addition, in Windows, the best way is to allocate memory with VirtualAlloc, he is not in the heap, nor in the stack is directly in the process of the address space to keep a fast memory, although the most inconvenient to use. But fast, and most flexible.


Storage content in heaps and stacks
Stacks:
When a function is called, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement). Then there are the parameters of the function, in most C compilers, the parameters are pushed from right to left, 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 first goes out of the stack, then the argument, and the last stack pointer points to the address that was first saved, the next instruction in the main function, where the program continues to run.

Heap: the size of the heap is usually stored in a byte at the head of the heap. The specifics of the heap are arranged by the programmer.

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

The AAAAAAAAAAA is assigned at run time;
And the BBBBBBBBBBB is determined at compile time;
However, in future accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).

Like what:

Copy Code code as follows:

void Main ()
{
char a = 1;
Char c[] = "1234567890";
Char *p = "1234567890";
A = c[1];
A = p[1];
Return
}

The corresponding assembly code
Copy Code code as follows:

10:a = c[1];
00401067 8A 4D F1 mov cl,byte ptr [ebp-0fh]
0040106A 4D FC mov byte ptr [ebp-4],cl
11:a = p[1];
0040106D 8B EC mov edx,dword ptr [ebp-14h]
00401070 8A mov al,byte ptr [edx+1]
00401073 FC mov-byte ptr [ebp-4],al

The first reads the elements in the string directly into the register CL, while the second reads the pointer value into the edx and reads the characters according to EdX, which is obviously slow.

Summary:
The difference between stacks and stacks can be seen in the following analogy:
Use stacks just like we eat in restaurants, just order (apply), pay, and eat (use), go after full, do not have to pay attention to cutting vegetables, vegetables, such as preparation and washing dishes, such as cleaning the pot, his advantage is fast, but the degree of freedom is small.

Using the heap is like eating your own food, more trouble, but more in line with their own taste, and freedom

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.