C/C ++ stack, stack, and static data zone details

Source: Internet
Author: User

Five memory partitions

InC ++Medium, memory is divided5Stack, stack, free storage zone, and global/Static 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 isNewAllocated memory blocks, their release compiler does not care about, by our applicationProgramTo control, generallyNewCorresponds toDelete. If the programmer does not release the program, the operating system will automatically recycle it after the program is completed.

Free storage areas areMallocThe allocated memory block is very similar to the heap, but it usesFreeTo end your life.

Global/In the static storage area, global variables and static variables are allocated to the same memory.CIn the language, global variables are classified into initialized and uninitialized.C ++There is no such distinction in it. They share the same memory zone.

Constant storage area, which is a special storage area. It stores constants and cannot be modified (of course, you can modify them by improper means, and there are many methods)

Clearly differentiate stack and stack

InBBSStack and stack differentiation issues seem 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.NewFirst, we should think that we allocated a heap of memory, so the pointerPWhat about it? The memory allocated is a stack memory, so this sentence means that a pointer pointing to a heap memory is stored in the stack memory.P. The program will first determine the size of memory allocated in the heap, and then callOperator newAllocate the memory, then return the first address of the memory, and put it into the stack.Vc6AssemblyCodeAs follows:

00401028 Push 14 h

0040102a Call Operator new (1, 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? YesDelete P? Australia, wrong. It should beDelete [] PTo tell the compiler that I deleted an array,Vc6According to the correspondingCookieInformation to release the memory.

Well, let's go back to our topic: What is the difference between stack and stack?

The main differences are as follows:

1Different management methods;

2, The space size is different;

3Whether fragments can be generated is different;

4And the growth direction is different;

5Different allocation methods;

6Different allocation efficiency;

Management Method: the stack is automatically managed by the compiler without manual control. For the stack, the release is controlled by the programmer and is easy to generate.Memory Leak.

Space size: Generally32In a 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, inVc6Below, the default stack space is 1 MB (as if yes, I cannot remember ). Of course, we can modify:

Open the project and choose the following menu:Project-> setting-> Link, InCategorySelectedOutputAnd thenReserveSet the maximum value andCommit.

Note:ReserveThe minimum value is4 byte;CommitIs retained in the page file of the virtual memory, which sets a greater value for Stack opening, which may increase the memory overhead and startup time.

Fragmentation problem: frequentNew/deleteIt 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. Stack has2Method: static and dynamic. Static allocation is completed by the compiler, such as local variable allocation. Dynamic AllocationAllocaThe function is allocated, but the dynamic stack allocation is different from the heap allocation. The dynamic stack 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 isC/C ++The function library provides a complex mechanism. For example, to allocate a piece of memory, the Library FunctionAlgorithm(For specific algorithms, refer to the data structure./Operating system) in the heap memory to search for available enough space, 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 and then return. Obviously, the heap efficiency is much lower than the stack efficiency.

From this we can see that compared with StackNew/deleteIt is easy to cause a large number of memory fragments. Because there is no special system support, the efficiency is very low. because it may lead to switching between the user State and the core state, the memory application costs 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,EBPAnd 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, or destroy the program's heap and stack structure to produce unexpected results.,Even if the above problem does not occur during your program running, you should be careful. Maybe it will crash at any time.DebugBut it is quite difficult :)

By the way, there is another thing. If someone puts the stack together, it means stack, not heap, huh, huh, clear?

StaticUsed 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, which leads to a problem.:How can I save the value of this variable in the function to the next call? 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 an object.,At the same time, we strive to avoid damaging the encapsulation of classes.,This requires that the member be hidden inside the class and invisible to the outside world.

StaticInternal 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; 3 is the application'sMain() The description and definition of global data before the function.

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.

StaticIntroduced to inform the compiler that the variables are stored in the static storage area of the program rather than the stack space.

Data members are initialized sequentially according to the sequence in which they appear. Note that when static members are nested, ensure that the nested members have already been initialized. The order of cancellation is the reverse order of initialization.

StaticAdvantages:

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 isPublicMember), In the program, according to the above format

To reference static data members.

PS:

(1)The static member function of the class belongs to the entire class rather than the class object, so it does notThisPointer, which causes

It only supports the static data and static member functions of the category.

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

(3)Since static members are declared in the class and operated outside of the class, it is somewhat special to take the address operation on them.

The variable address is a pointer to its data type, and the function address type is aNonmemberFunction pointer ".

(4)Because the static member function does not haveThisPointer, so it is almost equivalentNonmemberFunction.

It produces an unexpected benefit: BeingCallbackFunction, so that we canC ++AndC-based X W

IndowThe system is also successfully applied to thread functions.

(5) staticIt does not increase the space-time overhead of the program. On the contrary, it also shortens the access of the Child class to the static members of the parent class.

Time, saving sub-class memory space.

(6)Static data members are stored in<Definition or description>Add keywords beforeStatic.

(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 addingStaticTo avoid confusion with common static variables or objects;

The access control Letter of the member is not added during initialization.Private,PublicAnd so on;

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 impact of the parent class, you can define a static variable that is the same as the parent class in the subclass to avoid the impact 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 adopts a wonderful method:Name-manglingUsed to generate a unique flag.

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.