The difference between dynamic storage, static storage, heap, and stack

Source: Internet
Author: User

A binary image file that is formed after a compiled connection from a C + + program that contains:

Stacks, heaps, data segments (read-only data segments, initialized read and write data segments, uninitialized data segments, BBS), and code snippets.


1. Stack area (stack):

The compiler automatically assigns releases, stores the function's parameter values, and the local variables are equivalent. It operates in a manner similar to a stack in a data structure.

2. Heap Area (heap):

The heap allows a program to dynamically request a size of memory at run time.

Usually released by the programmer, if the programmer does not release, it may cause a memory leak.

The heap is different from the stack in the data structure, and its class is linked to the list.

3. Program code area: the binary code that holds the function body.

All statements are compiled and generated CPU instructions are stored in the code area.

4. Data segment: Consists of three parts:

<1> read-only data segments:
Read-only data segments are data that the program uses that are not changed, and use this data in a way that looks like a table-type operation, because these variables do not need to be changed, so they only need to be placed in read-only memory. Variables that are typically const-modified and literal constants used in programs are typically stored in read-only data segments.
<2> initialized read-write data segment:
Initialized data is declared in the program, and has the initial value of the variable, these variables need to occupy memory space, when the program executes, they need to be in a writable memory area, and have an initial value for the program to read and write. In a program, it is generally a global variable that has already been initialized, a static local variable that has already been initialized (the initialized variable of the static modifier)
<3> uninitialized Segment (BSS):
[
BSS usually refers to an area of memory that is used to hold uninitialized global variables and static variables in the program.
Features are read-write, and the BSS section will automatically clear 0 before the program executes.
]

Uninitialized data is declared in the program, but there are no initialized variables that do not need to occupy memory space before the program runs. Similar to the read-write data segment, it also belongs to the static data area. However, the data in this paragraph is not initialized. Uninitialized data segments are generated only during the initialization phase of the run, so its size does not affect the size of the destination file. In a program, there are generally no initialized global variables and static local variables that are not initialized.

Additional Instructions:

Constant Zone (special constant store, which belongs to the static storage area)
1) constants occupy memory, read-only state, never modifiable
2) A constant string is placed here, released by the system at the end of the program

--------------------------------------------------------------------------------------------------------------- --

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.
--------------------------------------------------------------------------------------------------------------- --
Dynamic Storage Area:
1. Stacks and heaps
Stack: The return address, parameters, and local variables of the function are stored.

Heap: We allocate the resulting space through the new operator and the malloc function.

The heap and stack are allocated in memory and are related to both the hardware architecture and the operating system.
x86 stacks are allocated from high address to low address, heap is assigned by low address to high address, but in Windows and Linux the location of heap and stack is opposite, there are some differences in the location of static data and code.
The stack belongs to the thread, and each thread will have its own stack.
2. Local automatic variables
stored in the stack area, in the stack area can actually be divided into several areas, they are called the stack frame, a stack frame is a function , need to call the function when the stack, the function return when the stack will pop up, So their life cycle is from the beginning of the function until the end of the function.
And what is stored in the stack frame, the stack frame holds the following things: The address of the parameter variable, the address of the local variable, return address (and the stack pointer and the base pointer, want to know this is what Baidu Bar)
3. Automatic variables (local variables without static declarations);
4. On-site protection and return address when function is called;
5. Dynamic variables
This is usually the space allocated by malloc new, and the life cycle is from the moment of allocation until the end of free.
--------------------------------------------------------------------------------------------------------------- --
Static storage mode
The so-called static storage method is the way to allocate a fixed amount of storage space during program compilation.
This storage method is usually defined as the variable definition of the storage unit and remains unchanged,

Until the end of the entire program. Global variables, static variables, and so on, belong to this kind of storage method.

Static Storage area:
Will exist and will be permanent and will not disappear, such data include constants, constant variables (const variables), static variables, global variables, and so on.
Static, constant, global variables are stored in the static storage area, they have been allocated after the program is compiled, the life cycle continues until the end of the program.
--------------------------------------------------------------------------------------------------------------- --
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: The compiler automatically allocates the release, the value of the stored function, the value of the local variable, 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 adjacent area. Released by the system after the program is finished.
4, the literal constant area: the constant string is placed here at the end of the program released by the system

5, program code area: the binary code that holds the function body.

--------------------------------------------------------------------------------------------------------------- --

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: Global variables, local static variables

The global variable is stored, and when the program starts executing, the global variable is allocated a storage area, and the program executes and is freed.

Dynamic storage: function parametric (assigning storage space to parameters when calling a function), local dynamic variable (auto register), function call field protection and return address, etc.

--------------------------------------------------------------------------------------------------------------- --
Two. Heap and Stack differences
1. How to Apply

(1) stack (SATCK): Automatically assigned by the system.


1) The program is run by the compiler automatically allocated a piece of continuous content, stored function parameter value, local variable value and so on.
For example, declare a local variable int b in the function, and the system automatically opens up space for B in the stack.
2) automatically released by the compiler at the end of the program

3) Stacks are automatically assigned by the system and cannot be controlled by programmers

4) 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.
5) Access mode, advanced out

(2) Heap:

1) Open another discontinuous storage area in memory. Usually distributed by the programmer to release,
2) If the programmer does not release, the system is collected at the end of the program
3) You should first 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.

The programmer is required to apply (call Malloc,realloc,calloc) and specify the size and release by the programmer. Easy to produce memory leak.eg:

    1. char p;
    2. p = (char *)malloc (sizeof (char));

However, p itself is in the stack.

----------------------------------------

In C, the malloc function

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. Restrictions on size of applications

(1) Stack: the stack in Windows is the data structure that extends to the bottom address, which is a contiguous area of memory (it grows in the opposite direction as the memory is growing). This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, under Windows, the size of the stack is 2M (and some say 1M, in short, a compile-time determination of the constant).

The size of the stack is fixed. If the requested space exceeds the remaining space on the stack, overflow will be prompted. Therefore, the space available from the stack is small.

(2) Heap: A heap is a data structure with a high address extension (it grows in the same direction as the memory) and is a discontinuous area of memory. This is due to the fact that the system uses a linked list to store the free memory address, which is naturally discontinuous, while the traversal direction of the list is from the bottom address to the 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.
3. System response:
(1) Stack: As long as the stack of space is larger than the application space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
(2) Heap: First of all should know that the operating system has a record of the free memory address of the list, but the system receives the application of the program, will traverse the list, the first space is larger than the requested space of the heap node, and then delete the node from the free list, 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 free statement in the code can properly release the memory space. In addition, the size of the found heap node is not necessarily exactly equal to the size of the request, and the system automatically re-places the extra portion into the idle list.

Description

(1) for the heap, frequent new/delete is bound to cause the memory space discontinuity, resulting in a large number of fragments, so that the program efficiency is reduced.

(2) for the stack, there is no problem,

4. Comparison of application efficiency
(1) The stack is automatically assigned by the system and is fast. But programmers can't control it.

(2) Heap is the memory allocated by malloc, the general speed is relatively slow, and easy to produce fragments, 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 of the address space to retain a piece of memory, although the most inconvenient to use. But the speed is fast, also the most flexible.

5. Storage content in heaps and stacks
(1) Stack: When a function is called, the address of the next statement in the main function of the first stack, followed by the parameters of the function, the arguments are in the stack from right to left, and then the local variables in the function. Note: 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 execution from that point.
(2) Heap: The size of the heap is usually stored in a heap with a byte in the head. The concrete contents of the heap are arranged by programmers.

6. Comparison of Access efficiency

(1) Heap: char *s1= "Hellow Tigerjibo"; Hellow Tigerjibo is determined in the compilation.

(2) Stack: char s1[]= "Hellow Tigerjibo"; Hellow Tigerjibo is assigned at run time;

Using arrays is faster than using pointers, and pointers in the underlying assembly need to be relayed in the edx register, and arrays are read on the stack.

The stack reads the elements in the string directly into the register CL, and the heap first reads the pointer value into EDX, which is obviously slow to read the characters according to EdX.

Add:

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.

7. Allocation Method:
(1) The heap is dynamically allocated and there is no statically allocated heap.

(2) There are two ways to allocate stacks: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. Dynamic allocations are allocated by the ALLOCA function, but the dynamic allocation of stacks is different from the heap. Its dynamic allocation is released by the compiler without the need for manual implementation.

--------------------------------------------------------------------------------------------------------------- ---

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.

The difference between dynamic storage, static storage, 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.