Compiled by C/C ++ProgramThe memory used is divided into the following parts: 1. Stack )-The compiler automatically assigns release, stores function parameter values, local variable values, and so on.. The operation method is similar to the stack in the data structure. Heap: the address of the space allocated by malloc, new, and so on. The address increases from low to high (released by programmers ). 2. Heap )-Generally, it is assigned and released by the programmer. If the programmer does not release the program, it may be recycled by the OS when the program ends.. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list. STACK: automatically allocates variables and space used by function calls (so-called local variables). The addresses are reduced from high to low; 3. Global (static)-storage of global variables and static variables is one piece,The initialized global variables and static variables are in one area. uninitialized global variables and uninitialized static variables are in another adjacent area. The program is released by the System. --> Data and BBS respectively 4. In the text constant area, the constant string is placed here, and is released by the system after the program ends. --> Coment Zone 5. ProgramCodeZone-stores the binary code of the function body. --> Code area Ii. Example Program This is written by a senior. It is very detailed. // Main. cpp Int A = 0; global initialization Zone Char * P1; uninitialized globally Main () { Int B; stack Char s [] = "ABC"; stack Char * P2; stack Char * P3 = "123456"; 123456 \ 0 is in the constant zone, and P3 is in the stack. Static int C = 0; Global (static) initialization Zone P1 = (char *) malloc (10 ); P2 = (char *) malloc (20 ); AllocateThe 10-byte and 20-byte areas are in the heap area. Strcpy (P1, "123456"); 123456 \ 0 is placed in the constant area, and the compiler may optimize it into a place with the "123456" that P3 points. } The variables defined in the function body are usually on the stack. The memory allocated by using malloc, calloc, realloc, and other functions is on the stack. All functions define a global volume in vitro. After the static modifier is added, all functions are stored in the global zone (static zone) no matter where they are located ), static variables defined by all functions in vitro are valid in this file and cannot be used in other files. Static variables defined in the function body are valid only in this function. In addition, strings such as "adgfdf" in the function are stored in the constant area. During function calling, a series of operations are performed on the stack to retain the site and PASS Parameters . The stack space is limited. The default value of VC is 2 MB. when stacks are insufficient, a large number of arrays and recursive function layers are usually allocated to the program. . It is important to know that when a function is returned after calling, it will release all the stack space of the function. The stack is automatically managed by the compiler, so you don't have to worry about it. heap dynamically allocates memory, and you can allocate large memory. However, poor use may cause memory leakage. and frequent malloc and free will generate memory fragments (somewhat similar to disk fragments ), because C searches for matching memory when allocating dynamic memory. Stack does not produce fragments. Accessing data on the stack is faster than accessing data on the stack through pointers heap and stack are two basic concepts that C/C ++ programming will inevitably encounter. First, both concepts can be found in the data structure book. They are both basic data structures, although the stack is simpler. In a specific C/C ++ programming framework, these two concepts are not parallel. The Research on the underlying machine code reveals that the stack is the data structure provided by the machine system, the heap is provided by the C/C ++ function library . Specifically, modern computers (serial execution mechanisms) directly support the stack data structure at the bottom of the Code. This is reflected in the fact that has a dedicated register pointing to the address of the stack, and a dedicated machine command to complete the operations of data in and out of the stack . This mechanism is characterized by high efficiency and limited data types supported by systems such as integers, pointers, and floating point numbers. It does not directly support other data structures. Due to the characteristics of stack, the use of stack is very frequent in the program. subprograms are called directly using stacks. The call command of the machine implicitly pushes the return address into the stack, and then jumps to the subprogram address. The RET command in the subprogram implicitly pops up the return address and jumps from the stack. the automatic variables in C/C ++ directly use the stack. This is why the automatic variables of the function become invalid when the function is returned. unlike the stack, the data structure of the heap is not a system (whether it is a machine system or an operating system) supported, but provided by the function library. the basic malloc/realloc/free functions maintain an internal heap data structure. when the program uses these functions to obtain new memory space, this function first tries to find available memory space from the internal heap, if there is no available memory space, the system calls are used to dynamically increase the memory size of the program data segment. The newly allocated space is first organized into the internal heap, and then return it to the caller in the appropriate form. when the program releases the allocated memory space, this memory space is returned to the internal Heap Structure, it may be processed properly (for example, merged into a larger idle space with other idle space) to make it more suitable for the next memory allocation application. This complex allocation mechanism is actually equivalent to a buffer pool (cache) for memory allocation. There are several reasons for using this mechanism: 1. system calls may not support memory allocation of any size. Some system calls only support fixed memory requests and their multiples (allocated by PAGE). This will cause a waste for a large number of small memory categories. 2. It may be expensive to request memory for system calls. System calls may involve switching between user and core states. 3. unmanaged memory allocation can easily cause memory fragmentation when a large amount of complex memory is allocated and released.
3. Theoretical knowledge of heap and stack 2.1 Application Method STACK: AutomaticallyAllocate. For example, declare a local variable int B in the function; the system automatically opens up space for B in the stack. Heap: The programmer needs to apply and specify the size. In C, the malloc Function For example, P1 = (char *) malloc (10 ); InC ++Use the new operator For example, P2 = (char *) malloc (10 ); But note:P1 and P2 are in the stack.. 2.2 System Response after application STACK: as long as the remaining space of the stack is larger than the applied space, the system will provide the programMemoryOtherwise, an exception is reported indicating stack overflow. Heap: First, you should knowThe operating system has an idle record.MemoryLinked list of addresses,When the system receives a program application, it traverses the linked list to find the heap node with the first space greater than the requested space, and then deletes the node from the idle node linked list, and set the space of the nodeAllocateTo the program. In addition, for most systems,The size of the allocation will be recorded at the first address in the memory space.In this way, the delete statement in the code can be correctly released.MemorySpace. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list. 2.3 Application size limit STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area.. This sentence means that the address at the top of the stack and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (OR 1 MB ).A constant determined during compilationIf the requested space exceeds the remaining space of the stack, overflow is displayed. Therefore, the space available from the stack is small. Heap: the heap is a data structure extended to the high address and a non-sequential memory area.This is becauseThe system uses a linked list to store idle memory addresses, which are naturally discontinuous, And the traversal direction of the linked list is from low address to high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large. 2.4 comparison of application efficiency: Stack automaticallyAllocateFast. But programmers cannot control it. Heap is composedAllocateOfMemoryIn general, the speed is slow and easy to generateMemoryFragments, but it is most convenient to use. In addition, in windows, the best way is to use virtualallocAllocate MemoryIt is not in the heap, nor in the stack. It is directly stored in the address space of the process.Memory, Although it is the most inconvenient to use. However, it is fast and flexible. Storage content in 2.5 heap and stack STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function.Note that static variables are not included in the stack. When the function call ends,The local variable first goes out of the stack, then the parameter, and the top pointer of the last stack points to the address of the first storage.That is, the next instruction in the number of primary functions, where the program continues to run. Heap: Generally, the heap size is stored in one byte in the heap header.The specific content in the heap is arranged by the programmer. 2.6 comparison of access efficiency Char S1 [] = "aaaaaaaaaaaaa "; Char * S2 = "bbbbbbbbbbbbbbbbb "; Aaaaaaaaaaa is assigned a value at the runtime; Bbbbbbbbbbbbb is determined during compilation; However,In future access,StackThe array on is faster than the character string (such as heap) pointed to by the pointer. For example: # I nclude 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]; 00401067 8A 4D F1 mov Cl, byte PTR [ebp-0Fh] 0040106a 88 4D FC mov byte PTR [ebp-4], Cl 11: A = P [1]; 0040106d 8B 55 EC mov edX, dword ptr [ebp-14h] 00401070 8A 42 01 mov Al, byte PTR [edX + 1] 00401073 88 45 FC mov byte PTR [ebp-4], Al First, you can directlyCharacterThe elements in the string are read into the register Cl, and the second type must firstPointerRead the value to EDX.CharacterObviously, it is slow. 2.7 summary: The difference between stack and stack can be seen in the following metaphor: Using Stacks is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it, without having to worry about the preparation work, such as cutting and washing dishes, as well as the cleaning and tail work such as washing dishes and flushing pots, his advantage is fast, but his degree of freedom is small. Using heap is like making your favorite dishes. It is troublesome, but it suits your taste and has a high degree of freedom. 2.8 comparison According to the above knowledge,Stack is a function provided by the system. It features fast and efficient. Its disadvantage is that it has restrictions and data is not flexible. Stack is a function provided by function libraries. It features flexibility and convenience and wide range of data adaptation, however, the efficiency is reduced.The stack is the system data structure, which is unique for processes/Threads. The heap is the internal data structure of the function library, which is not necessarily unique. Memory for different heap shards cannot be operated on each other. Stack space is divided into static allocation and dynamic allocation. Static allocation is completed by the compiler, such as automatic variable allocation. Dynamic Allocation is completed by the alloca function. The stack does not need to be released dynamically (automatically), so there is no release function. For the sake of portable programs, dynamic stack allocation is not encouraged! Heap space allocation is always dynamic. Although all data spaces are released back to the system at the end of the program, precise memory application/release matching is the basic element of a good program. The heap and stack of the operating system, as mentioned above, will not be mentioned much. There is also the heap and stack in the data structure. These are different concepts. Here, the heap actually refers to a Data Structure (meeting the heap nature) of the priority queue. The 1st elements have the highest priority; stack is actually a mathematical or data structure that meets the needs of the advanced and later stages. Although the stack is called a connection, they still have a lot of difference. The connection is only due to historical reasons. the heap and stack grow in the opposite direction , | -------------- | low address | heap | | -------------- | ||| | I | || |^| | stack | high address ----------------- so the heap and stack in the computer are often explained in one piece Generally, it is not necessary to create dynamically. The most annoying way is to use new items as local variables and delete them immediately. Reason 1. The stack shard ratio is fast. You only need one command to allocate all the local variables. 2. The stack will not contain memory fragments 3. Stack Object Management Of course, this is also required in some situations, such 1. large objects 2. The object must be constructed or analyzed at a specific time. 3. Classes only allow dynamic creation of objects. For example, most classes in VCL Of course, you cannot avoid using heap objects either. What is the role of heap memory and stack memory?Heap: random orderSTACK: Advanced and later Bytes ---------------------------------------------------------------------------------------------------------------------- Why on the stack?Allocate MemoryCompared to stackAllocate MemorySlow? To open up heap space, you must use system functions to directly modify the stack.Pointer Heap SpaceManagementSystem Accounting is required. The stack space can be managed by the compiler or stored in a Processor register. Stack space release requires system management. Stack release can be discarded directly. The heap space needs to pass throughPointerIndirect reference, so access will be slow Remember to see such a paragraph in the thread above apue2, which roughly means that a thread has its own stack and can be stored on the stack.Allocate MemoryFor example, if this thread calls pthread_exit () to return this structPointerYou should be especially careful later, because it is very likely that the value of the Members in this struct changes. This can be understood because the resources of the same process with threads are shared, when this thread exits, the previously used stacks are likely to be occupied by other threads, but it also says that if malloc does not, For example, in the stack into an int, as long as the esp-4 can be, On the stack, the system must recordAllocate MemoryTo release ---------------------------------- Memory AllocateThere are three methods: 1. From the static storage areaAllocate.MemoryWhen the program is compiledAllocateOkay, this one.MemoryIt exists throughout the entire running period of the program. For example, global variables and static variables. 2. Create a stack. Storage of local variables in a function when executing a functionUnitCan be created on the stack, and these stores are used at the end of function execution.UnitAutomatically released. StackMemory AllocateComputation is built into the processor's instruction set, which is highly efficient,AllocateOfMemoryCapacity Limited. 3. From the stackAllocate, Also known as dynamicMemory Allocate. The program uses malloc or new to apply for any numberMemoryThe sequencer is responsible for when to use free or delete for release.Memory. DynamicMemoryThe survival time is determined by us. It is very flexible to use, but there are also the most problems. ---------------------------------------- Generally, a stack usually refers to a stack.Memory. It is used to store local variables, temporary variables, function parameters, and return addresses of programs. Variable in this areaAllocateAnd release are automatically performed by the system. User participation is not required. The heap (first-in-first-out) space is performed by the user.AllocateAnd released by the user. ========================================================== ========================================================== === |