C ++ memory allocation methods-heap, stack, free storage, global/static storage, and constant Storage

Source: Internet
Author: User
Tags control characters

  StackThat is, the storage areas for variables allocated by the compiler when needed and automatically cleared when not needed. The variables are usually local variables and function parameters. In a process, the user stack is located at the top of the user's virtual address space, and the compiler uses it to call functions. Like the heap, the user stack can be dynamically expanded and reduced during program execution.

  HeapThat is, the memory blocks allocated by new. Their release compilers are not controlled and controlled by our applications. Generally, a new one 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 heap can be dynamically expanded and reduced.

  Free storage ZoneIt 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.

  Global/static storage Zone, Global variables and static variables are allocated to the same memory. In the previous C language, the global variables are divided into initialized and uninitialized (the initialized global variables and static variables are in one area, and the uninitialized global variables and static variables are in another adjacent area, objects that are not initialized at the same time can be accessed and manipulated through void *, and are released by the system after the program ends. This distinction is not found in C ++, they share the same memory zone.

  Constant storage ZoneThis is a special storage area where constants are stored and cannot be modified (of course, you can modify them by improper means, and there are many 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         14h

  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? Oh, wrong. It should be Delete [] P to tell the compiler: I deleted an array and vc6 will release the memory according to 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 stacks, 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 4G From this perspective, there is almost no limit on the heap memory. But for stacks, there is usually a certain amount of space. For example, under vc6, the default stack space size is 1 m (It seems that you cannot remember ). Of course, we can modify it: Open the project and choose Project> setting> link from the following menu. Select output in 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 Problems: For the heap, frequent New/delete operations will inevitably lead to discontinuous memory space, resulting in a large number of fragments and reduced 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 heap, 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. The dynamic allocation is implemented by the malloc function, but the dynamic allocation of stacks is different from that of stacks. The dynamic allocation of stacks is released by the compiler without manual implementation.

  Allocation EfficiencyThe stack is the data structure provided by the machine system. The computer will provide support for the stack at the underlying layer: assign a special register to store the stack address, and pressure the stack to output the stack with 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 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?

Static is used to control the storage and visibility of variables.

When a variable defined in a function is executed to its definition, the compiler allocates space for it on the stack, the space allocated by the function on the stack is released at the end of the function execution. This creates a problem: If you want to save the value of this variable in the function to the next call, how to implement it? The easiest way to think of is to define a global variable, but defining a global variable has many disadvantages, the most obvious drawback is that the access range of the variable is broken (so that the variables defined in this function are not controlled by this function ). A Data Object is required to serve the entire class rather than a specific object, and the encapsulation of the class is not damaged. That is, the member is required to be hidden inside the class and invisible to the outside world.

Static Internal Mechanism:

Static data members must exist at the beginning of the program. Because the function is called during the running of the program, static data members cannot allocate space and initialize it in any function. In this way, there are three possibilities for its space allocation. One is the header file of the class's external interface, where there is a class declaration; the other is the internal implementation of the class definition, there is a member function definition for the class, and the third is the global data description and definition before the main () function of the application.

Static data members must actually allocate space, so they cannot be defined in the class declaration (only data members can be declared ). The class declaration only declares the "size and specification" of a class and does not actually allocate memory. Therefore, it is wrong to write a definition in the class declaration. It cannot be an external definition of the class declaration in the header file, because it will duplicate the definition in multiple source files that use the class.

Static is introduced to inform the compiler that the variables are stored in the static storage area of the program rather than the stack space. static data members are initialized in sequence according to the sequence in which they appear. Note that when static members are nested, make sure that the nested members have been initialized. The order of cancellation is the reverse order of initialization.

Static advantages:

Memory can be saved because it is public to all objects. Therefore, for multiple objects, static data members only store one object for sharing. The value of a static data member is the same for each object, but its value can be updated. You only need to update the value of the static data member once to ensure that all objects have the same value after the update, which improves the time efficiency. When referencing static data members, use the following format:

<Class name >:: <static member name>

If the access permission of the static data member is allowed (that is, the Public Member), you can reference the static data member in the program in the preceding format.

  

PS:

(1) The static member function of the class belongs to the entire class rather than the Class Object. Therefore, it does not have the this pointer, which leads to the ability to parse static data and static member functions of the class only.

(2) static member functions cannot be defined as virtual functions.

(3) because static members are declared in the class and operated outside of the class, it is somewhat special to perform the address fetch operation on them. The variable address is a pointer to its data type, the function address type is a "nonmember function pointer ".

(4) because the static member function does not have the this pointer, it is almost equivalent to the nonmember function, and the result produces an unexpected benefit: To become a callback function, this allows us to combine C ++ and C-based X Window systems, and also successfully apply them to thread functions.

(5) Static does not increase the space-time overhead of the program. On the contrary, It shortens the access time of the subclass to the static members of the parent class and saves the sub-class memory space.

(6) Add the keyword "static" before <definition or description> to the static data member.

(7) static data members are stored statically, so they must be initialized.

(8) static member Initialization is different from general data member initialization:

Initialization is performed in the external class without static before, so as to avoid confusion with general static variables or objects;

During initialization, the access permission control characters private and public of the member are not added;

During initialization, the scope operator is used to indicate the class to which it belongs;

So we can get the format of static data member initialization:

<Data type> <class name >:< static data member name >=< value>

(9) to prevent the influence of the parent class, you can define a static variable of the same as the parent class in the subclass to avoid the influence of the parent class. Here, we need to note that static members are shared by the parent class and subclass, but we have repeatedly defined static members. Will this cause errors? No, our compiler uses a wonderful method: Name-mangling is used to generate a unique flag.

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.