Heap: it is a space shared by everyone, divided into global heap and partial heap. The global heap is empty.
The local heap is the space allocated by the user. Heap is allocated when the operating system initializes the process and runs
You can also request additional heap to the system during the operation, but remember to return the heap to the operating system after it is used up. Otherwise
Memory leakage. Static data, such as Static data and characters, is usually stored in the heap.
String constants and so on. Resources are usually stored in the heap after being loaded. All threads of a process have these heaps,
Therefore, synchronization and mutex should be considered for heap operations. The compiled data segments in the program are all heap one.
.
STACK: It is unique to a thread and stores its running status and Local Automatic variables. When the stack starts with a thread
Every thread stack is independent from each other. Therefore, the stack is thread safe. Each C +
+ The data members of objects also exist in the stack. Each function has its own stack, which is used in functions.
Parameters. The operating system automatically switches the stack when switching the thread, that is, switches the SS/E
SP register. Stack space does not need to be explicitly allocated or released in advanced languages.
Stack and stack differences
I. prerequisites-program memory allocation
The memory occupied by a c/C ++ compiled program is divided into the following parts:
1. stack: the stack is automatically allocated and released by the compiler, storing the function parameter values and local variables.
. The operation method is similar to the stack in the data structure.
2. heap-usually assigned and released by the programmer. If the programmer does not release the heap
It may be recycled by the OS. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
.
3. Global (static)-stores global variables and static variables.
The initialized global variables and static variables are in the same area. uninitialized global variables and uninitialized
The static variable is in another adjacent area. -The program is released by the system after it is completed.
4. Text Constant Area-constant strings are placed here. The program is released by the system.
5. program code area-stores the binary code of the function body.
Ii. Example Program
CODE: [Copy to clipboard]
---------------------------------------------------------------------
-----------
// 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 {row. content} is in the constant area, and p3 is in the stack.
Static int c = 0; Global (static) initialization Zone
P1 = (char *) malloc (10 );
P2 = (char *) malloc (20 );
The allocated 10-byte and 20-byte areas are in the heap area.
Strcpy (p1, "123456"; 123456 {row. content} is placed in the constant area, and the compiler may point it
"123456" is optimized to a single place.
}
Ii. Theoretical knowledge of heap and stack
2.1 Application Method
Stack:
Automatically assigned by the system. For example, declare a local variable int B in the function; the system automatically runs in the stack.
Open up space for B
Heap:
The programmer needs to apply and specify the size. In c, the malloc Function
For example, p1 = (char *) malloc (10 );
Use the new operator in C ++
For example, p2 = (char *) malloc (10 );
But note that p1 and p2 are in the stack.
2.2
System Response after application
STACK: the system will provide the program with memory as long as the remaining space of the stack is greater than the applied space. Otherwise, an exception will be reported.
Stack Overflow prompt.
Heap: First, you should know that the operating system has a linked list that records the idle memory address. When the system receives
When applying, the linked list will be traversed to find the heap node with the first space greater than the requested space.
The node is deleted from the idle node linked list and the space of the node is allocated to the program.
The system records the size of the allocation at the first address in the memory space.
The delete statement can correctly release the memory space. In addition, the size of the heap node is not necessarily
Exactly equal to the applied size. The system automatically puts the excess parts into 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
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 M (or may be 1 M, which is a constant determined during compilation), if the requested space
Overflow is displayed when the remaining space of the stack is exceeded. 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 because the system uses the chain
The idle memory address stored in the table is not consecutive, And the traversal direction of the linked list is from the low address
High address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the heap gets null
They are flexible and large.
2.4 comparison of application efficiency:
The stack is automatically allocated by the system, which is faster. But programmers cannot control it.
Heap is the memory allocated by new, which is generally slow and prone to memory fragments.
Convenience.
In addition, in WINDOWS, the best way is to use VirtualAlloc to allocate memory.
Instead of using the stack, you can directly store a fast memory in the address space of the process, although it is the most inconvenient to use. However
Fast and flexible.
Storage content in 2.5 heap and stack
STACK: when calling a function, the first entry to the stack is the next instruction in the main function (function call statement
The next executable statement), and then the parameters of the function, in most C Compilers
, The parameter is from right to left into the stack, and then is the local variable 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 stack points to the most open
The address where the program starts to run, that is, the next instruction in the main function.
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, the array on the stack is faster than the string pointed to by the pointer (such as the heap.
For example:
CODE: [Copy to clipboard]
---------------------------------------------------------------------
-----------
Void main ()
{
Char a = 1;
Char c [] = "1234567890 ";
Char * p = "1234567890 ";
A = c [1];
A = p [1];
Return;
}
Corresponding assembly code
CODE: [Copy to clipboard]
---------------------------------------------------------------------
-----------
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
The first type reads the elements in the string directly into the cl register, while the second type reads
Read the needle value to edx.
Reading characters by edx is obviously 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 (sending an application), paying, and eating (using ),
When you are full, you don't have to worry about cooking, washing, and other preparation work, washing dishes, flushing pots, etc.
It is quick, but has a small degree of freedom.
Using heap is like making your favorite dishes by yourself. It is troublesome, but it suits your taste,
It also has a high degree of freedom.
It is generally considered that c is divided into these storage areas
1 stack-automatically assigned and released by a compiler
2 heap-it is generally assigned and released by the programmer. If the programmer does not release it, the program may be recycled by the OS at the end of the program.
3. In the global zone (static zone), the storage of global variables and static variables is put together, and the initialized global variables and static variables are stored in one
The uninitialized global variables and the uninitialized static variables are in another adjacent area.
-Release after the program ends
4. There is also a special place to place constants. -Release after the program ends
The variables defined in the function body are usually defined on the stack. What is obtained by the memory allocation function such as malloc, calloc, and realloc?
On the stack. In vitro, all functions define the global volume. After the static modifier is added, all functions are stored in the global zone no matter where they are (static
The static variables defined by all functions in vitro are valid in this file and cannot be used in other files.
The static value is valid only in the function body. In addition, strings such as "adgfdf" in the function are stored in the constant area.
For example:
Code:
Int a = 0; // global initialization Zone
Char * p1; // not initialized 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 );
// The allocated 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 with "123456" pointed to by p3.
}
In addition, during function calling, a series of operations will be performed on the stack to retain the site and transmit parameters.
The stack space is limited. The default value of vc is 2 MB. The stack is not enough. Generally, the program allocates a large number of arrays and recursive function layers.
Deep. It is important to know that when a function is returned after calling, it will release all the stack space of the function. Stack is automatically managed by the compiler
Yes, you don't have to worry about it.
Heap dynamically allocates memory, and you can allocate a large amount of memory. However, poor use may cause memory leakage.
In addition, frequent malloc and free will produce memory fragments (a bit similar to disk fragments), because c searches for matching when allocating dynamic memory.
Memory. Stack does not produce fragments.
Accessing data on a stack is faster than accessing data on a stack through a pointer.
Generally, stack is the same as stack, that is, stack, and heap.
The stack is first imported and then output, and is generally grown from a high address to a low address.
Another reprinted article:
Heap and stack are two basic concepts that C/C ++ programming will inevitably encounter. First, both concepts can be discussed in Data
In the structure book, they are all 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 can reveal that the stack is a machine system.
The data structure provided by the system, while 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 dedicated mailing
The memory points to the address where the stack is located, and there are dedicated machine commands to complete the data import and export operations on the stack.
This mechanism is characterized by high efficiency and limited data types supported by systems such as integers, pointers, and floating point numbers,
Other data structures are not directly supported. Due to the characteristics of stack, the use of stack is very frequent in the program. Subprograms
Stack is used directly. The call command of the machine implicitly pushes the return address into the stack, and then jumps to the subroutine address.
While the ret command in the subroutine implicitly pops up the return address from the stack and jumps to the operation. The automatic variables in C/C ++ are directly used.
In the stack example, this is why the automatic variables of the function become invalid when the function returns.
Unlike the stack, the stack data structure is not supported by the system (whether a machine system or an operating system), but provided by the function library.
The basic malloc/realloc/free function maintains 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, it tries
Use System calls 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 to the caller in the appropriate form. When the program releases the allocated memory space, this memory space will be returned to the internal Heap Structure and may
Suitable for processing (such as merging with other idle space into larger idle space), so as to better suit the next memory allocation application. This complex set
The allocation mechanism is actually equivalent to a buffer pool (Cache) allocated by memory. 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 sizes and multiples.
(Distribution by PAGE); this will cause a waste for a large number of small memory categories.
2. System Call memory application may be expensive. 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.
Stack and stack comparison
From the above knowledge, we can see that stack is a function provided by the system, featuring fast and efficient. Its disadvantage is its limitation and data is not flexible. Stack is a function library.
The features provided are flexible and convenient, and the data is widely adapted, but the efficiency is reduced. Stack is the system data structure.
The process/thread is unique; the heap is the internal data structure of the function library, not necessarily unique. Memory allocated by different heaps cannot be operated on each other. Stack space
It can be divided into two types: static allocation and dynamic allocation. Static allocation is completed by the compiler, such as automatic variable allocation. Dynamic Allocation
The alloca function is complete. The stack does not need to be released dynamically (automatically), so there is no release function. Stack
Dynamic Allocation is not encouraged! Heap space allocation is always dynamic, although all the data space will be released back at the end of the program
System, but the precise request for memory/release memory matching is the basic element of a good program