Memory area division, memory allocation, a constant storage area, heap, stack, free store, global area [C ++] [Memory Management] (rpm)

Original: https://www.cnblogs.com/JCSU/articles/1051579.html

Reference links:

 https://blog.csdn.net/weixin_40306859/article/details/90232204?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

 http://www.freesion.com/article/271421321/

 

 https://blog.csdn.net/One_L_Star/article/details/81901186

 

A is divided into several memory areas c,
1. Stack - automatically allocated by the compiler release
2. stack - typically assigned by the programmer release, if the programmer does not release, may be recovered at the end of the program by the OS
3. Global Area (static region), global variables and static variables are stored in one and initialized global and static variables in a region, and uninitialized variables uninitialized global static variable region adjacent to the other one. - End of program release
4. In addition there is a special place to put constant. - End of program release
                                                                                                                                              
variables defined in the body of the function is usually on the stack with the distribution function malloc, calloc, realloc and other memory allocated on the heap is obtained. All functions are global in vitro defined amount, plus the static modifier wherever are stored in the global area (static area), all functions in static variables defined in vitro effective representation in the document, to other documents can not extern used in the body of the function definition is valid only in the static function expressed in vivo. Further, the function of "adgfdf" This string is stored in the constant region. such as:

int A = 0 ; // global initialization region 
char * P1; // global uninitialized area 
void main () 
{ 
    int B; // stack 
    char S [] = " ABC " ; // stack 
    char * P2; // Stack 
    char * P3 = " 123456 " ; // 123456} {post.content in the constant region, p3 on the stack 
    static  int C = 0 ; // global (static) zone initialize 
    P1 = ( char *) the malloc ( 10); // apportioned come in 10-byte area of the heap area 
    P2 = ( char *) the malloc ( 20 ); // allocate 20 bytes have come in the heap area region 
    strcpy (P1, " 123456 " );
     // 123456 {post.content} in the constant region, the compiler might p3 it points to "123456" into an optimization 
}

II. In C ++, memory is divided into five areas, they are the heap, stack, free store, global / static storage area and the constant storage area
1. stacks,
are those allocated by the compiler when needed, without the need when the automatic storage area clear of variables. Variables which are typically local variables, functions and other parameters.
2. heap, those that block of memory allocated by new, never mind their release compiler, to control by our application, a new general would correspond to a delete. If a programmer is not freed, then at the end of the program, the operating system will automatically recover.
3. The free store, that is, those memory blocks allocated by malloc and so on, he and the heap is very similar, but it is free to end their lives.
4. Global / static storage area , global variables and static variables are allocated to the same memory, the previous C, global variables is divided into initialized and uninitialized in C ++ which do not have this distinction, and their common occupy the same memory area.
5. Constant storage area, which is a special storage area inside the store they are constant, not allowed to modify (Of course, you can also change through non-legitimate means)

III. To talk about the relationship and differences between heap and stack
Specifically, modern computer (serial execution mechanism), directly support data structures in the code underlying stack. This is reflected in a dedicated register points to the address of the stack is located, with a dedicated machine instructions to complete the data stack the operand stack. This design feature is efficiency, limited data to support, generally an integer, pointer, etc. floating point data types supported by the system directly, does not directly support other data structures. Because of this feature of the stack, the stack is the use of very frequent in the program. Call to a subroutine stack is directly completed. Machine implicit call instruction in the return address onto the stack, then the operation jumps to a subroutine address and the ret instruction subroutine return address from the stack pop implied and the jump operation. C / C ++ are examples of the direct use of automatic variable stack, which is why when the function returns, the function of automatic variable automatic failure cause.

And different stack, heap data structure is not by the system (either system or machine operating system) support, but by the library. Basic malloc / realloc / free function maintains the interior of the heap data structure a set. When a program uses these functions to get new memory space, this function first tries to find available from within the heap memory space, memory space can be used if no, then tried to use the system call to dynamically increase the memory size of the program data segment the new allocation of space to get into the interior of the heap was first organized to go, and then return the appropriate form to the caller. When the program releases the allocated memory space, this memory space is returned to the inside of the stack structure, it may be an appropriate process (such as free space, and other are combined into a larger free space), the memory allocation to a more suitable application. This complex distribution mechanism is actually equivalent to a memory allocation pool (Cache), the use of this mechanism has the following several reasons:
1. The system calls may not support memory allocation of any size. Some system calls the system supports only fixed-size and multiple memory requests (by page allocation); this is the case for a large number of small memory classification is wasteful.
2. The application memory system calls may be costly. System call may involve the conversion of user mode and kernel mode.
3. Under no management memory allocation release operation in a large number of complex memory allocation is likely to cause memory fragmentation.

Comparative heap and stack
from the above knowledge the stack is provided by the system function, characterized by fast and efficient, disadvantage is limited, data is not flexible; the stack is a function provided by the library function, characterized by flexible, extensive data adaptation surface, but there is a certain efficiency decreases. Stack is a system data structure for process / thread is unique; heap library is an internal data structure, not necessarily unique. Different heap allocation of memory to operate with each other. Stack spatial distribution of static and dynamic allocation of two kinds. Static allocation is done compiler, such as assigning variable automatic (auto) is. Dynamic allocation is done by alloca function. Dynamic allocation without releasing the stack (automatic), there is no release function. For the sake of portable programs, dynamically allocated stack operation is not to be encouraged! Allocate heap space is always dynamic, although the end of the program all the data space will be released back into the system, but the precise application memory / release memory match is an essential element of a good program.

    1. debris problem: For a heap in terms of frequent new / delete will inevitably lead to discontinuity of memory space, causing a lot of debris, so reducing the efficiency of the procedure . For the stack is concerned, it will not have this problem, because the stack is advanced out of the queue, they are so one to one that will never have a memory block pop-up from the middle of the stack, before he pops up, stack contents above him backward has been ejected, details can> reference data structure, here we are not going to discuss it.
    2. growth direction: For a heap is concerned, the growth direction is upward, i.e. toward the direction of increasing memory addresses; for the stack in terms of its growth direction is downwards, is reduced in the direction of growth of the memory address.
    3. Assign way: heap is allocated dynamically, not statically allocated heap. There are two kinds of stack allocation: static allocation and dynamic allocation. Static allocation is done compiler, such as the allocation of local variables. Dynamically allocated by alloca allocation function, but dynamic stack allocation and heap are different, his dynamic allocation is released by the compiler, we do not need to manually achieve.
    4. Assign Efficiency: the stack is a data structure of the machine provided by the system, the computer will provide the underlying support for a stack: a special register storage allocated address stack, the stack has a dedicated push instruction is executed, which determines the efficiency of the stack relatively high . Stack is the C / C ++ library provided, its mechanism is complicated, for example, in order to allocate a memory library functions will follow a certain algorithm (specific algorithm may reference a data structure / operating system) search heap memory available space of sufficient size, if there is no space of sufficient size (probably due to too many fragmented memory), it is possible to call the system function to increase the memory space program data segment, so there is ample opportunity to be assigned to the size of the memory, and then return. Obviously, heap much lower efficiency than the stack.

    A clear distinction between heap and stack :
    on the bbs, the problem of distinguishing the heap and stack, seems to be an eternal topic, shows that this often confusing for beginners, so I decided to take his first surgery.
    First, we give an example:

  

void f()
{ 
    int* p=new int[5];
}

This simple sentence contains the heap and stack, to see new, we should think first of all, we allocate a piece of heap memory, then the pointer p it? He is a piece of stack memory allocation, so what it means is this: store a pointer to a pointer p heap memory in the stack memory . The program will first determine the size of the memory allocated on the heap and then call operator new to allocate memory, then return to the first address of this memory, placed on the stack, he compiled code under VC6 as follows:
    00,401,028 the Push 14H
    0040102A Call operator new (00.40106 million)
    0040102F the Add ESP,. 4
    00,401,032 MOV DWORD PTR [EBP-. 8], EAX
    00,401,035 MOV EAX, DWORD PTR [EBP-. 8]
    00,401,038 MOV DWORD PTR [EBP-. 4], EAX
    here, we do not release the memory for simplicity , then how to release it? Delete p is it? Australia, wrong, should be the Delete [] the p- , which is to tell the compiler: I delete an array, VC6 would be to release the memory according to the corresponding Cookie information work.
    Well, we go back to our topic: the heap and stack What is the difference?
    The main difference from the following:
    1, different management;
    2, spaces of different sizes;
    3, can produce different fragments;
    4, different growth directions;
    5 except distribution;
    6, different distribution efficiency;
    management: For stack is concerned, is managed automatically by the compiler, we do not need to manually control; For a heap, the release is controlled by a programmer working, prone to memory leak.
    Space: In general, 32-bit system, 4G heap memory space can be achieved from this point of view heap memory is almost no limitation. But for the stack is concerned, there is usually a certain amount of space, for example, in VC6 below, the default stack space is 1M (like, can not remember). Of course, we can modify:
    Open the project, and then click the Action menu as follows: Project-> Setting-> Link, select Output in Category, and then set the maximum and commit stack in the Reserve.
Note: reserve a minimum of 4Byte; commit is retained in the virtual memory page file inside a large stack will make it opens up a larger set of values, may increase the memory overhead and start-up time.
    Heap and stack compared to the use of a large number of new / delete, likely to cause a large amount of memory fragmentation; because there is no special support system is inefficient; because the switch may lead to user mode and kernel mode, the memory of the application, the cost becomes more expensive. So stack it is the most widely used in the program, even calling functions also use the stack to complete, during the function call parameters, return address, EBP, and local variables are used to store a stack of way. Therefore, we recommend you try to use the stack rather than the heap.

Further comparison of the efficiency of access:
Code:

char s1[] = "aaaaaaaaaaaaaaa";
char *s2 = "bbbbbbbbbbbbbbbbb";

aaaaaaaaaaa at run-time assignment;
and bbbbbbbbbbb is determined at compile time;
however, in the future access in an array on the stack than the string pointed to by a pointer (e.g., stack) fast .
such as:

void main()
{
    char a = 1;
    char c[] = "1234567890";
    char *p ="1234567890";
    a = c[1];
    a = p[1];
    return;
}

Corresponding assembly code
10: A = C [. 1];
00,401,067. 8A 4D Fl MOV Cl, byte PTR [EBP-0Fh]
0040106A 88 4D the FC MOV byte PTR [EBP-. 4], Cl
. 11: A = P [. 1];
8B EC 55 MOV EDX 0040106D, DWORD PTR [EBP-14H]
00.40107 million. 8A Al MOV 42 is 01, byte PTR [EDX +. 1]
00,401,073 88 45 PTR the FC byte MOV [EBP-. 4], Al
a first direct reading put a string of elements in the read register cl, while the second will have to first read edx pointer value in, in accordance with edx read character, apparently slow.
    whether heap or stack, we need to prevent cross-border phenomenon occurrence (unless you are deliberately making cross-border), because the result is either a cross-border program crash or destroy the program heap, stack structure, produce unexpected results, even in the course of your program is running, there is no occurrence of the above the problem, you still have to be careful, you never know when you collapse out, writing code stable and secure is the most important

Guess you like

Origin www.cnblogs.com/lh03061238/p/12533225.html