C + + language learning-memory allocation management

Source: Internet
Author: User
Tags stack pop

1 , a C-compiled program consumes memory in the following sections

1. Stack (stack)-the program is automatically assigned by the compiler when it is run, storing the parameter value of the function, the value of the local variable, etc. It operates in a manner similar to a stack in a data structure. Automatically released by the compiler at the end of the program.

2. Heap area-open another storage area in memory. Usually released by the programmer, if the programmer does not release, the program ends may be recycled by the OS. Note that it is not the same as the heap in the data structure, but the distribution is similar to the linked list.

3. Global zone (static zone)-the compiler allocates memory at compile time. The storage of global variables and static variables is placed in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another contiguous area. -released by the system after the program is finished

4, literal constant area-the constant string is put here. Released by the system after the program is finished

5. Program code area-binary code that holds the function body.

Example Program

1 Charaaa[3*2048*2048];2 intA =0;//Global Initialization Zone3 Char*P1;//Global Uninitialized Zone4 intMain () {5 intb//Stack6 CharS[] ="ABC";//stack char *p2;//Stack7 Char*P3 ="123456";//"123456/0" in the constant area, p3 on the stack. static int c =0;//Global (Static) initialization zone8P1 = (Char*) malloc (Ten); 9P2 = (Char*) malloc ( -); Ten //areas that are allocated 10 and 20 bytes are in the heap area.  Onestrcpy (P1,"123456");//123456/0 place in constant area A}
View Code

2 , there are three ways to allocate memory:

1, from the static storage area allocation. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables, static variables.
2, create on the stack. When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.
3, allocated from the heap, also known as dynamic memory allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by the programmer and is very flexible to use, but if space is allocated on the heap, it is the responsibility to reclaim it, otherwise the running program will have a memory leak, and frequently allocating and releasing different sizes of heap space will result in heap fragments.

3. Heap vs. Stack comparison
3.1 How to apply
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 himself and indicate the size of the malloc function in C, which is the new operator in C + +.
such as P1 = (char *) malloc (10); P1 = new CHAR[10];
such as P2 = (char *) malloc (10); P2 = new CHAR[20];
But note that P1, p2 itself is in the stack.
3.2 Response of the system after application
Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
Heap: First of all should know that the operating system has a record of the free memory address of the list, when the system receives the application of the program, it will traverse the list, look for the first space is larger than the requested space of the heap node, and then delete the node from the list of idle nodes, and the node's space allocated to the program.
For most systems, the size of this allocation is recorded at the first address in the memory space, so that the DELETE statement in the code can properly free up the memory space.
Because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.
3.3 Application Size Limits
Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.
Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory.    This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.
3.4 Comparison of application efficiency
The stack is automatically assigned by the system and is faster. But programmers can't control it.
Heap is the memory allocated by new, the general speed is relatively slow, and prone to memory fragmentation, but the most convenient to use.
In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, not the stack, but directly in the process of the address space to retain a fast memory, although the most inconvenient to use. But the speed is fast, also the most flexible.
3.5 Storage contents in stacks and stacks
Stack: In a function call, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement), and then the parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that static variables are not in the stack.
When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.
Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.
3.6 Comparison of Access efficiency
Char s1[] = "a";
char *s2 = "B";
A is assigned at run time, while B is determined at compile time, but in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap). Like what:

    
1 intMain () {2     CharA =1;3     CharC[] ="1234567890";4     Char*p ="1234567890";5A = c[1];6A = p[1];7     return 0;8}
View Code

The corresponding assembly code

10:a = c[1];
00401067 8A 4D F1 mov cl,byte ptr [ebp-0fh]
0040106A 4D FC mov byte ptr [ebp-4],cl
11:a = p[1];
0040106D 8B-EC mov edx,dword ptr [ebp-14h]
00401070 8A mov al,byte ptr [edx+1]
00401073 FC mov byte ptr [ebp-4],al
The first reads the elements in the string directly into the register CL, while the second one reads the pointer values into edx and then reads the characters according to EdX, which is obviously slow.

3.7 Summary
The main differences between heaps and stacks are by 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. Of course, this value can be modified.
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 will be no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there is never a memory block from the middle of the stack pop, before he pops up, in the back of his upper stack content has been ejected, detailed reference data structure can be referenced.
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 assigned by the Malloca 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.
Regardless of whether it is a heap or stack, avoid the occurrence of cross-border phenomena (unless you deliberately cross it), because the result of the cross-border is either a program crash, or destroy the program heap, stack structure, produce unexpected results.

comparison between 4.new/delete and Malloc/free
From a C + + perspective, allocating heap space using new can call the class's constructor, and the malloc () function is just a function call that does not call the constructor, and the parameter it accepts is a unsignedlong type. Similarly,Delete calls the destructor before releasing the heap space, and the free function does not.   

1 classtime{2      Public:3Time (int,int,int,string);4~Time () {5cout<<"Call time ' s destructor by:"<<name<<Endl;6 }7     Private:8     inthour;9     intmin;Ten     intsec; One     stringname; A }; -Time::time (intHintMintSstringN) { -Hour=h; themin=m; -Sec=s; -Name=N; -cout<<"Call time ' s constructor by:"<<name<<Endl; + } -     intMain () { +Time *T1; At1= (time*) malloc (sizeof(time)); at Free (t1); -Time *T2; -T2=NewTime (0,0,0,"T2"); - Delete T2; -}
View Code

Properties of variables: data type, storage type, scope, storage period.

1, data type: We are familiar with int, char, long, etc., nothing to say;

2, Storage type: auto, static, register, extern four kinds;

3, scope: Refers to the program can be used in the area of the variable;

4. Storage period: Refers to the storage period of the variable in memory.

Storage type: described in the following scope description.

Scope: There are local variables and global variables

Local variables:

Automatic variable (dynamic local variable, i.e. defined within function, static local variable declared without static, leaving function, value disappears)

Static local variables: (Defined inside a function, static local variables declared with static, values are preserved when leaving the function)

Register variables: (frequently used variables, placed in the CPU register, C + + is not necessary, because it is like built-in functions, how to handle the compiler to say, leave the function, the value disappears) formal parameters (when the parameter is passed, more cases are defined as automatic variables or register variables)

Global variables:

External variables (variables defined outside the outer function, other files can be used after the extern declaration, disappear at the end of the program)

Static external variables (other files may not be used, disappear at the end of the program)

Storage period: Dynamic storage and static storage

Dynamic storage:

Automatic variable (this function is valid)

Register variable (this function is valid)

Formal parameters (valid for this function)

Static storage:

Static local variable (valid for this function)

Static global variable (this file is valid)

External variables (other files can be referenced)

There are also constant storage, dynamic application space (NEW,MALLOC), etc., which are described in detail above.

C + + language learning-memory allocation management

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.