C ++ stack, stack, free storage, global/static storage, and constant storage)

Source: Internet
Author: User

1. Memory occupied by a c/C ++ compiled program is divided into the following parts:
1. stack: the stack zone is automatically allocated and released by the compiler, and stores function parameter values and local variable values. The operation method is similar to the stack in the data structure.
2. heap-usually allocated and released by programmers (malloc/free, new/delete). If the programmer does not release, the program may be recycled by the operating system after the program ends. Note that it is different from the heap stone in the data structure. The allocation method is similar to the linked list. Among them, malloc/free is allocated and released, which can also be called a free storage zone.
3. Global (static)-the storage of global variables and static variables is put together, and the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. -After the program ends, the system is released (in C ++, the initialization and uninitialized jointly occupy a memory zone ).
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
This is written by a senior. It is 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 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 is placed in the constant area, and the compiler may optimize it to a place that corresponds to "123456" pointed to by p3. }

3. Theoretical knowledge of heap and stack

The main differences between stack and stack are as follows:

2.1 different management methods
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 for 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: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. 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 fragmentation issues
For the heap, frequent new/delete operations will inevitably lead to memory space disconnections, resulting in a large number of fragments, reducing program efficiency.
For the stack, this problem does not exist, because the stack is a back-to-first-out queue, they are so one-to-one correspondence that it is impossible to have a memory block popped up from the middle of the stack, before it is popped up, the post-stack content on it has been popped up.

2.4 growth direction
For the heap, the growth direction is upward, that is, the direction for increasing the memory address.
For the stack, the growth direction is downward, and the direction is to decrease the memory address.

2.5 Allocation Method
The heap is dynamically allocated without static allocation.
There are two stack allocation methods: static allocation and dynamic allocation. The compiler completes static allocation, such as local variable allocation. Dynamic Allocation is distributed by the alloca function. However, the dynamic allocation of stacks is different from that of heap. The dynamic allocation of stacks is released by the compiler, and we don't need to think about it manually.

2.6 Allocation Efficiency
The stack is the data structure provided by the machine system. The computer will provide support in the underlying Stack: allocate a special register to store the stack address, and the output stack of the Pressure Stack has a dedicated command execution, this determines the high efficiency of the stack.
The heap is provided by the c/c ++ function library, and its mechanism is very complicated. For example, to allocate a piece of memory, library functions search for available enough space in the heap memory according to certain algorithms. If there is not enough space (probably because there are too many fragments ), it is possible to call the system function to increase the memory space of the program data segment, so that there is a chance to allocate enough memory and then return. Obviously, the heap efficiency is much lower than the stack efficiency.

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 statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In WINDOWS, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. 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 linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the 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:
The stack is automatically allocated by the system, which is faster. But programmers cannot control it.
The heap is the memory allocated by new, which is generally slow and prone to memory fragments. However, it is most convenient to use.
In addition, in WINDOWS, the best way is to use VirtualAlloc to allocate memory. Instead of heap or stack, it is to reserve a fast memory in the address space of the process, 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 stack points to the address of the initial storage, that is, the next instruction in the main function, 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, the array on the stack is faster than the string pointed to by the pointer (such as the heap. For example:

   #include    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
The first type reads the elements in the string directly into the cl register, while the second type reads the pointer value into edx. Reading the characters based on 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 food (sending an application), paying for it, and eating (using it). If you are full, you can leave, 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.

1. Memory Allocation:
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 at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list. The keywords that may be used are new, malloc, delete, and free.
STACK: the Compiler automatically allocates and releases the stack, stores the function parameter values, and values of local variables. The operation method is similar to the stack in the data structure.

2. Application Methods:
Heap: the programmer must apply and specify the size. In c, the malloc function is like p1 = (char *) malloc (10). In C ++, the new operator is used. But note that p1 and p2 are in the stack. Because they can still be considered as local variables.
STACK: automatically allocated 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.

3. system response:
Heap: the operating system has a linked list that records the idle memory address. 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, delete the node from the idle node linked list and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space so that the delete statement in the code can correctly release the memory space. 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.
STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.

4. size limit:
Heap: it refers to the data structure extended to the high address and is a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the 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.
STACK: in Windows, a stack is a data structure extended to a low address and a continuous memory area. This sentence means that the top stack address and the maximum stack capacity are pre-defined by the system. In WINDOWS, the stack size is fixed (a constant determined during compilation). If the requested space exceeds the remaining space of the stack, overflow is displayed. Therefore, the space available from the stack is small.

5. Efficiency:
Heap: Memory allocated by new. It is generally slow and prone to memory fragments. However, it is most convenient to use. In addition, in WINDOWS, the best way is to use VirtualAlloc to allocate memory, which is not in the heap, nor in the stack. It is to reserve a fast memory directly in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.
STACK: the stack is automatically allocated by the system, and the speed is fast. But programmers cannot control it.

6. content storage:
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.
STACK: When a function is called, 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: 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 address of the initial storage, that is, the next instruction in the main function, where the program continues to run.

7. access efficiency:
Heap: char * s1 = "Hellow Word"; determined during compilation;
STACK: char s1 [] = "Hellow Word"; it is assigned a value at runtime. Using arrays is faster than using pointers, because pointers need to be transferred using the edx register in the underlying assembly, and arrays can be directly read on the stack.

Ps: Too Many reprints .. The source cannot be found ..

Related Article

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.