"Yoga theme"-memory allocation (1)

Source: Internet
Author: User

Abstract: memory management has always been a minefield of C/C ++ programming. Everyone is reluctant to touch her, but sometimes they have to touch it. Although the use of smart pointer in C ++ can completely avoid using pointers, further understanding of pointers helps us compile more efficient code, it also helps us understand the previously written programs.

Five memory partitions
In C ++, memory is divided into five areas: heap, stack, free storage, global/static storage, and constant storage.
Stack is the storage area for variables that are automatically allocated by the compiler when necessary and clear when not needed. The variables are usually local variables and function parameters.
Heap is the memory blocks allocated by new. Their release compilers are not controlled and controlled by our applications. Generally, a new compiler corresponds to a Delete. If the programmer does not release the program, the operating system will automatically recycle it after the program is completed.
The free storage zone is the memory blocks allocated by malloc and so on. It is very similar to the heap, but it uses free to end its own life.
In the global/static storage area, global variables and static variables are allocated to the same memory. In the previous C language, global variables were divided into initialized and uninitialized ones, in C ++, there is no such distinction. They share the same memory zone.
Constant storage zone, which is a special storage zone. It stores constants and does not allow modifications (of course, you can modify them by improper means, and there are many methods, in the article "const thinking", I have provided 6 methods)

Clearly differentiate stack and stack
On the BBS, the distinction between heap and stack seems to be an eternal topic. It can be seen that beginners are often confused about this, so I decided to take him first.
First, let's take an example:
Void F () {int * P = new int [5];}
This short sentence contains the heap and stack. When we see new, we should first think that we allocated a heap memory. What about the pointer P? It allocates a stack memory, so this sentence means that the stack memory stores a pointer P pointing to a heap memory. The program will first determine the size of memory allocated in the heap, then call operator new to allocate the memory, then return the first address of the memory, and put it into the stack, the assembly code in vc6 is as follows:
00401028 push 14 h
0040102a call operator new (00401060)
0040102f add ESP, 4
00401032 mov dword ptr [ebp-8], eax
00401035 mov eax, dword ptr [ebp-8]
00401038 mov dword ptr [ebp-4], eax
Here, we have not released the memory for simplicity, So how should we release it? Is it delete p? Australia, the error should be "Delete [] P" to tell the compiler: I deleted an array and vc6 will release the memory based on the cookie information.
Well, let's go back to our topic: What is the difference between stack and stack?
The main differences are as follows:
1. Different management methods;
2. Different space sizes;
3. Whether fragments can be generated is different;
4. Different Growth directions;
5. Different allocation methods;
6. Different Allocation Efficiency;
Management Method: For stacks, it is automatically managed by the compiler without manual control. For heaps, the release work is controlled by programmers and memory leak is easily generated.
Space size: Generally, in a 32-bit system, the heap memory can reach 4 GB. From this perspective, there is almost no limit on the heap memory. But for the stack, there is usually a certain amount of space. For example, under vc6, the default stack space is 1 MB (as if so, I cannot remember ). Of course, we can modify:
Open the project and choose Project> setting> link, select output from category, and set the maximum value and commit of the stack in reserve.
Note: The minimum reserve value is 4 byte. Commit is retained in the page file of the virtual memory. Compared with the general setting, commit makes the stack open up a large value, memory overhead and startup time may be increased.
Fragmentation problem: 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 will not exist, because the stack is an advanced and outgoing 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 the pop-up, the post-stack content has been popped up. For details, refer to the data structure. We will not discuss it one by one here.
Growth direction: For the stack, the growth direction is upward, that is, the direction to the memory address increase; For the stack, the growth direction is downward, is to increase towards memory address reduction.
Allocation Method: The heap is dynamically allocated without static allocation. There are two stack allocation methods: static allocation and dynamic allocation. Static allocation is completed by the compiler, such as local variable allocation. Dynamic Allocation is implemented by the alloca function, but the stack dynamic allocation is different from the heap dynamic allocation. Its Dynamic Allocation is released by the compiler without manual implementation.
Allocation Efficiency: the stack is the data structure provided by the machine system, and the computer will provide support for the stack at the underlying layer: allocate a dedicated register to store the stack address, the output stack of the Pressure Stack has dedicated Command Execution, which 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 space in heap memory based on certain algorithms (for specific algorithms, refer to data structures/operating systems, if there is not enough space (probably because there are too many memory 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, then return. Obviously, the heap efficiency is much lower than the stack efficiency.
From this point, we can see that compared with the stack, the use of a large number of new/delete operations may easily cause a large amount of memory fragments; because of the absence of dedicated system support, the efficiency is very low; because it may lead to switching between the user State and the core state, the memory application will become more expensive. Therefore, stacks are the most widely used in applications. Even function calls are completed using stacks. The parameters and return addresses in the function call process are as follows, both EBP and local variables are stored in stacks. Therefore, we recommend that you use stacks instead of stacks.
Although the stack has so many advantages, but because it is not so flexible as the heap, sometimes it is better to allocate a large amount of memory space.
Whether it is a heap or a stack, it is necessary to prevent cross-border phenomena (unless you intentionally cross-border it), because the cross-border result is either a program crash, either it is to destroy the heap and stack structure of the program and generate unexpected results. Even if the above problem does not occur during your program running, you should be careful, maybe it will collapse at some time. At that time, debugging was quite difficult :)
By the way, there is another thing. If someone puts the stack together, it means stack, not heap, huh, huh, clear?

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.