Heap/stack/dynamic storage mode/static storage mode

Source: Internet
Author: User

Dynamic storage mode

Dynamic storage is the way in which storage space is allocated dynamically as needed during program operation. A dynamic storage variable is the allocation of a storage unit during the execution of the program, which is released immediately after use. A typical example is the formal parameter of a function, which does not assign a storage unit to a parameter when the function is defined, but only assigns it when the function is called, releasing the function immediately after it is invoked. If a function is called multiple times, the storage unit of the parameter variable is allocated and released repeatedly.

Static storage mode

The so-called static storage method is the way to allocate a fixed amount of storage space during program compilation. This is usually done by defining the storage unit at the time the variable is defined and remaining unchanged until the end of the program. Global variables, static variables, and so on, belong to this kind of storage method.

Summarize

From the above analysis, static storage variables are always present, while dynamic storage variables sometimes exist and disappear. We have also described the lifetime of the variable as a result of the variable storage method. The lifetime represents the time the variable exists. The lifetimes and scopes describe the characteristics of variables from two different angles of time and space, both linked and differentiated. The type of storage that a variable belongs to is not only judged by its scope, but also by a clear description of storage types.

Allocation of user storage space in memory (three types):

Program Area: Store program statements

Static storage: The global variable is stored, and when the program begins execution, the global variable is allocated a storage area, and the program executes and is released.

Dynamic Storage: Stores the following data: function form parameters. Allocating storage space to parameters when calling a function, automatic variables ( local variables without static declarations ) , field protection and return addresses at function invocation, etc.;

Stack

Stacks are the stores of variables that are allocated by the editor when needed, automatically cleared when not needed, and the variables are usually local variables. function parameters, and so on.

Heap

is those right new allocated memory block, their release editor not to tube, by our application to control, generally a new will correspond to a delete. If the programmer does not release it, the operating system will automatically recycle after the program finishes.

The difference between heaps and stacks is mainly:

1. Different management methods: for the stack, is automatically managed by the compiler, without our manual control, for the heap, release work by the programmer control, easy to produce memory leak.

2. Fragmentation can be different: 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 is no problem because the stack is advanced and out of the queue, and he

They are so one by one correspondence that it is never possible to have a memory block pop up from the middle of the stack before he pops up, and the content of the last stack above him has been popped

3. Direction of growth: for the heap, the direction of growth is upward, that is, to the memory address of the direction of increase, for the stack, its growth direction is downward, is toward the memory address of the direction of growth.

4. Allocation method: The heap is dynamically allocated and there is no statically allocated heap. 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 ALLOCA 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.

5. 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.

Summarize

Heap and Stack, due to the use of a large number of new/delete, prone to large amounts of memory fragmentation, due to lack of 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.
Stacks have so many benefits, but because they are not as flexible as the heap, sometimes allocating a lot of memory space is better than a heap.
Whether it is a heap or stack, to prevent the occurrence of cross-border phenomenon (unless you deliberately make it out of bounds), because the result of the cross-border is either a program crash, or destroy the program heap, stack structure, produce unexpected results, even in the course of your program, did not occur above the problem, you still have to be careful, Maybe when it's going to blow up, then debug is pretty hard:)

The following article reproduces the difference between stacks and heaps.

Source: http://www.chinaitpower.com/2005September/2005-09-13/206685.html

I. Preliminary knowledge-memory allocation of the program

The memory used by a program compiled by C + + is divided into the following sections
1. Stack (stack)-Automatically allocated by the compiler to release, store the function parameter value, local variable value and so on. It operates in a manner similar to a stack in a data structure.
2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the end of the program may be recycled by the OS. Note that it is not the same as the heap in the data structure, the distribution is similar to the list, hehe.
3, Global Zone (Static)-, 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 area adjacent. -System release after the program is finished
4, literal 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 function body.
Ii. Examples of procedures
It was written by a predecessor, very detailed
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 in the constant area, p3 on the stack.
static int c = 0; global (static) initialization zone
P1 = (char *) malloc (10);
P2 = (char *) malloc (20);
Areas that are allocated 10 and 20 bytes are in the heap area.
strcpy (P1, "123456"); 123456 in the constant area, the compiler might optimize it to a place with the "123456" that P3 points to.
}
Ii. theoretical knowledge of heaps and stacks
2.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
such as P1 = (char *) malloc (10);
Using the new operator in C + +
such as P2 = (char *) malloc (10);
But note that P1, p2 itself is in the stack.
2.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, in addition, The size of this allocation is recorded at the first address in this memory space, so that the DELETE statement in the code can properly free up the memory space. Also, 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.
2.3 Application Size Limits
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.
2.4 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 it's fast and flexible.
2.5 Storage contents in stacks 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.
2.6 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:
#include <stdio.h>
void Main ()
{
char a = 1;
Char c[] = "1234567890";
Char *p = "1234567890";
A = c[1];
A = p[1];
Return
}
The corresponding assembly code
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 one reads the pointer values into EDX, which is obviously slow to read the characters according to EdX.


2.7 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.
The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.

The difference between heap and stack is mainly divided into:
The operating system stack and stack, as said above, not much to say.
There are heaps and stacks of data structures that are different concepts. The heap here actually refers to a data structure of the priority queue (which satisfies the heap nature), the 1th element has the highest priority, and the stack is actually a mathematical or data structure that satisfies the advanced nature of the post.
Although stacks, stacks are said to be linked together, but they are still very different, connected to call only because of historical reasons.

Heap/stack/dynamic storage mode/static storage mode

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.