A detailed description of C + + memory allocation-heap, stack, free storage, global/static storage, and constant storage

Source: Internet
Author: User
Tags class definition stack pop

Stacks , which are the stores of variables that are allocated by the compiler when needed, and automatically purged when not needed. The variables inside are usually local variables, function parameters, and so on. In a process, the user stack at the top of the user's virtual address space is compiled with it to implement the function invocation. As with heaps, the user stack can expand and contract dynamically during program execution.

  Heap , which is the memory blocks allocated by new, their release compiler does not go to the tube, by our application to control, generally a new will correspond to a delete. If the programmer does not release it, the operating system will automatically recycle after the program finishes. The heap can be expanded and shrunk dynamically.

  The free storage area , which is the memory blocks allocated by malloc, is very similar to the heap, but it ends up living with no.

  Global /static storage , global variables and static variables are allocated in the same piece of memory, in the previous C language, the global variables are divided into initialized and uninitialized (initialized global variables and static variables in a block, uninitialized global variables and static variables in another area adjacent, While uninitialized object stores can be accessed and manipulated through void*, the system frees itself after the program ends, there is no such distinction in C + +, and they occupy the same chunk of memory.

  constant Storage , which is a special piece of storage, they are stored in constant, not allowed to modify (of course, you have to pass the improper means can also be modified, and many methods)

  Clearly differentiate stacks from stacks

On BBS, heap and stack of the problem, seems to be an eternal topic, this shows that the beginner is often confused, so I decided to take his first surgery.

  First, let's give an example:

void F () {int* p=newint[5];}

This short sentence contains the heap and stack, see new, we should first think that we have allocated a heap of memory, then the pointer p? He allocates a stack of memory, so the meaning of this sentence is: In the stack memory is stored in a pointer to a heap of memory p. The program will first determine the size of the memory allocated in the heap, then call operator new to allocate memory, and then return the first address of the memory, put in the stack, his assembly code under VC6 is as follows:

00401028push 14h

0040102Acall operator New (00401060)

0040102Fadd esp,4

00401032mov DWORD ptr [Ebp-8],eax

00401035mov Eax,dword ptr [ebp-8]

00401038mov DWORD ptr [Ebp-4],eax

Here, we do not release the memory for the sake of simplicity, then how to release it? Is it delete p? Oh, wrong, it should be delete []p, this is to tell the compiler: I delete an array, VC6 will be based on the corresponding Cookie information to do the work of releasing memory.

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

The main differences are from the following points:

1, different management methods;

2, the space size is different;

3, can produce different fragments;

4, the growth direction is different;

5, the distribution method is different;

6, the allocation efficiency is different;

  Management mode : For the stack, is automatically managed by the compiler, without our manual control, for the heap, the release of work by the programmer control, easy to produce memory leak.

  Space size : Generally speaking, in 32-bit system, heap memory can reach 4G space, from this point of view heap memory is almost no limit. But for the stack, generally there is a certain amount of space, for example, under the VC6, the default stack space is 1M (as if it is not clear). Of course, we can modify: Open the project, the Operation menu is as follows: Project->setting->link, select Output in Category, then set the maximum and commit of the stack in the reserve. Note: The reserve minimum value of 4byte;commit is reserved in the virtual memory of the page file, it is set to a large size stack will open up a larger value, may increase the memory overhead and startup time.

  fragmentation Problem : For the heap, frequent new/delete is bound to cause memory space discontinuity, resulting in a large number of fragments, so that program efficiency is reduced. For the stack, there is no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there will never be a memory block from the middle of the stack pop-up, before he pops up, in the back of his upper stack content has been ejected, detailed can refer to the data structure, here we are no longer one by one discussed.

  Growth Direction : For the heap, the direction of growth is upward, that is, to the memory address of the direction of increase, for the stack, its growth direction is downward, is to reduce the memory address direction of growth.

  allocation method : The heap is dynamically allocated and there are no statically allocated heaps. Stacks are allocated in 2 ways: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is allocated by the malloc function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is released by the compiler without our manual implementation.

  allocation efficiency : The stack is the data structure provided by the machine system, the computer will support the stack at the bottom: allocate the address of the special register storage stack, the stack stack has a special instruction execution, which determines the efficiency of the stack is high. The heap is provided by C + + function library, its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for available enough space, if there is not enough space (possibly due to too much memory fragmentation), It is possible to invoke the system function to increase the memory space of the program data segment, so that there is a chance to divide the memory in sufficient size and then return. Obviously, the heap is much less efficient than the stack.

From here we can see that heap and stack, due to the use of a large number of new/delete, is prone to large amounts of memory fragmentation, because there is no dedicated system support, inefficient, due to the possibility of triggering user-state and nuclear mentality of the switch, memory applications, the cost becomes more expensive. So the stack is the most widely used in the program, even if the call of the function is done by the stack, the parameters in the function call, the return address, the EBP and the local variables are all stored in a stack. So, we recommend that you try to use stacks instead of heaps.

Although the stack has so many advantages, it is not so flexible compared to the heap, sometimes allocating a lot of memory space, or heap better.

Whether it is a heap or stack, to prevent the occurrence of cross-border phenomenon (unless you deliberately make it out of bounds), because the result of the cross-border is either a program crash, or destroy the program heap, stack structure, produce unexpected results, even in the course of your program, did not occur above the problem, you still have to be careful, Maybe when it's going to blow up, then debug is pretty hard:)

By the way, one more thing, if someone put the stack together said, it means stack, not a heap, hehe, clear?

Static used to control the storage and visibility of variables

A variable defined inside a function, when the program executes to its definition, the compiler allocates space on the stack, and the space allocated by the function on the stack is freed at the end of the function execution, creating a problem: What if you want to save the value of this variable in a function to the next call? The easiest way to think of is to define a global variable, but there are many drawbacks to defining a global variable, and the most obvious disadvantage is that it destroys the scope of access to the variable (the variable defined in this function is not only controlled by this function). A data object is required to serve the entire class rather than an object, while at the same time trying not to break the encapsulation of the class, which requires that the member be hidden inside the class and not visible externally.

the internal mechanism of static :

A static data member must exist at the beginning of a program run. Because a function is called in a program run, a static data member cannot allocate space and initialization within any function. In this way, its spatial allocation has three possible places, one is the header file as the outer interface of the class, there is the class declaration, and the second is the inner implementation of the class definition, there is the member function definition of the class, and the third is the global data declaration and definition in front of the main () function of the application.

Static data members are actually allocated space, so they cannot be defined in the declaration of a class (only data members can be declared). A class declaration declares only "dimensions and specifications" of a class and does not actually allocate memory, so it is wrong to write a definition in a class declaration. It also cannot be defined externally in the header file for the class declaration, because that would cause duplicate definitions in multiple source files that use the class.

Static is introduced to tell the compiler that the variables are stored in the program's static store rather than on the stack, and that static data members are initialized sequentially in the order in which they are defined, noting that when static members are nested, the nested members are guaranteed to be initialized. The order of elimination is the inverse order of the initialization.

the advantages of static :

Can save memory because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to be shared. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is updated once, it is guaranteed that all objects access the same value after the update, which can improve time efficiency. When you reference a static data member, the following format is used:

< class name >::< static member name >

If the access permission for a static data member is allowed (that is, a member of public), the static data member can be referenced in the program in the format described above.

  

Ps:

(1) A static member function of a class is an object of the entire class rather than a class, so it does not have the this pointer, which causes it to access only the static data and static member functions of the class.

(2) A static member function cannot be defined as a virtual function.

(3) because the static member is declared in the class, the operation is outside, so it takes the address operation, it is somewhat special, the variable address is a pointer to its data type, the function address type is a "nonmember function pointer".

(4) Since the static member function does not have this pointer, it is almost identical to the nonmember function, resulting in an unexpected benefit: being a callback function allows us to combine the C + + and c-based X Window systems, while also successfully Used for thread functions.

(5) Static does not increase the space-time overhead of the program, but she also shortens the subclass's access time to the static members of the parent class, saving the memory space of the child class.

(6) static data members in the < definition or description > before adding the keyword static.

(7) A static data member is stored statically, so it must be initialized.

(8) Static member initialization differs from general data member initialization:

Initialization is performed outside of the class body, and the front is not static, so as not to be confused with the general static variables or objects;

The access control that is not added to the member at initialization is private, public;

The scope operator is used when initializing to indicate the class to which it belongs;

So we derive the format of the static data member initialization:

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

(9) To prevent the effect of the parent class, you can define a static variable in the subclass that is the same as the parent class to mask the effect of the parent class. Here's one thing to note: we say that static members are shared by the parent and subclass, but we have statically defined static members, does that cause errors? No, our compiler uses a neat trick: name-mangling is used to generate unique flags.

Three ways to allocate memory allocations in C + +:

1. Allocation from static storage: At this point the memory is allocated at the time of program compilation and exists throughout the program's run. Global variables, static variables, etc. are stored here.

2. Allocation in the stack: when the relevant code is executed, it is automatically released at the end of execution. Local variables are stored here. The stack memory allocation operation is built into the processor's instruction set, which is efficient but limited in capacity.

3. Allocation in the heap: dynamic allocation of memory. With New/malloc when opened, Delete/free when released. The lifetime is specified by the user and is flexible. But there are memory leaks and other issues.

Common memory errors and Countermeasures

1. Memory allocation is not successful, but is used. Countermeasure: Check whether the allocation was successful before using memory. Judge with P!=null.

2. Memory allocation is successful, uninitialized is used. The default value of memory does not have a uniform standard. Most compilers use 0 as the initial value, but not exactly. Countermeasure: The initial value is assigned when the memory is initialized.

3. Memory operation is out of bounds. Countermeasures: only be careful.

4. Freed up memory, still in use.

(1) Use a wild pointer showing delete and free. Action: Release the memory and set the pointer to null. (2) Use the wild pointer of the implicit delete and free. The main point is that the function returns a pointer or reference to the stack memory. Countermeasures: Of course, do not return to it.

5. No memory is released, causing a memory leak. Use New/malloc to open up the memory, useless delete/free release. Countermeasures: The number of new and delete must be the same; the number of malloc and free must be the same; new[] and []delete must correspond.

A detailed description of C + + memory allocation-heap, stack, free storage, global/static storage, and constant storage

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.