C/C ++ Memory Allocation Method

Source: Internet
Author: User

 

Link: http://blog.csdn.net/jing0611/article/details/4030237

1. Memory Allocation Method

There are three memory allocation methods: [1] allocating from the static storage area. InnerProgramIt is allocated during compilation, and this Part exists.Program. For example, global variables and static variables. [2] Create a stack. When a function is executed, the storage units of local variables in the function can be created on the stack. When the function is executed, these storage units are automatically released. Stack memory allocation computation is built into the processor's instruction set, which is highly efficient, but the memory capacity allocated is limited. [3] distributed from the stack, also known as dynamic memory allocation.ProgramUse malloc or new to apply for any amount of memory during running,ProgramThe worker is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory isProgramThe user decides that the use is very flexible, but if the space is allocated on the stack, it is the responsibility to recycle it; otherwise, the runningProgramMemory leakage may occur, and frequent allocation and release of heap space of different sizes will generate fragments in the heap.2.ProgramMemory spaceOneProgramDivide the memory blocks allocated to the operating system into four areas, as shown in.
Code Area) ProgramMemory space
Data Area)
Heap Area)
Stack Area)
Compiled by C/C ++ProgramMemory usage is divided into the following parts: 1. Stack is automatically allocated and released by the compiler, stores the local variables, function parameters, returned data, and return addresses allocated to run the function. The operation method is similar to the stack in the data structure. 2. heap is generally composedProgramAssigned to members for release. IfProgramMembers are not released,ProgramIt may end with the OS recycle. The allocation method is similar to the linked list. 3. The Global zone (static) Stores global variables, static data, and constants.ProgramRelease the system after completion. 4. Put the constant string in the text constant area here.
ProgramThe system releases the instance. 5,ProgramThe Code area stores the binary code of the function body (class member functions and global functions. The following is an example.Program,
Int A = 0; // The Global initialization zone char * P1; // The Global initialization zone int main (){
Int B; // The stack char s [] =/"ABC/"; // stack char * P2; // stack char * P3 =/"123456 /"; // 123456 // 0 is in the constant zone, and P3 is in the stack. Static int C = 0; // global (static) initialization zone p1 = new char [10];
P2 = new char [20];
// The allocated and byte areas are in the heap area. Strcpy (P1,/"123456/"); // 123456 // 0 is placed in the constant area, the compiler may optimize it to the/"123456/" to which P3 points .}
3. Comparison Between Stack and stack3.1 application method 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: RequiredProgramManually apply,AndSpecify the size. In C, the malloc function and in C ++ is the new operator. For example, P1 = (char *) malloc (10); P1 = new char [10];
For example, P2 = (char *) malloc (10); P2 = new char [20];
But note that P1 and P2 are in the stack. 3.2 system response stack after application: the system willProgramProvides memory. Otherwise, an exception is reported, indicating stack overflow. Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receivesProgramWhen applying, the linked list will be traversed to find the heap node with the first space greater than the requested space, and then delete the node from the idle node linked list,AndAllocate the space of the nodeProgram. For most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. Because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list. 3.3 apply for a size limit Stack: in windows, the stack is a data structure extended to the low address and is a continuous memory area. This sentence indicates the top of the stack.Address andThe maximum stack capacity is pre-defined by the system. In Windows, the stack size is 2 m (OR 1 m, which is a constant determined during compilation ), if the requested space exceeds the remaining space of the stack, overflow is displayed. Because
Therefore, the space available from the stack is small. Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large. 3.4 The Application Efficiency Comparison stack is automatically allocated by the system, and the speed is faster. HoweverProgramMembers cannot be controlled. Heap is the memory allocated by new. It is generally slow and prone to memory fragments, but it is most convenient to use. In addition, in windows, the best way is to use virtualalloc to allocate memory. Instead of heap or stack, it simply keeps a fast memory in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible. Storage in 3.5 heap and stackContentSTACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note that static variables are not included in the stack. When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function,ProgramContinue to run at this point. Heap: Generally, the heap size is stored in one byte in the heap header. Heap detailsContentYesProgramPersonnel Arrangement. 3.6 comparison of access efficiency char S1 [] =/"/";
Char * S2 =/"B /";
A is assigned a value at runtime, while B is determined at compilation. However, in future access, the array on the stack is faster than the string pointed to by the pointer (such as the heap. For example:
Int main (){
Char A = 1;
Char C [] =/"1234567890 /";
Char * P =/"1234567890 /";
A = C [1]; A = P [1]; return 0 ;}
Corresponding assembly code
10: A = C [1];
00401067 8A 4D F1 mov Cl, byte PTR [ebp-0Fh]
0040106a 88 4D FC mov byte PTR [ebp-4], Cl
11: A = P [1];
0040106d 8B 55 EC mov edX, dword ptr [ebp-14h]
00401070 8A 42 01 mov Al, byte PTR [edX + 1]
00401073 88 45 FC mov byte PTR [ebp-4], Al
FirstReadThe elements in the stringReadTo register Cl, and the second type should first set the pointer ValueReadTo edX, And then according to edXReadReading characters is obviously slow. 3.7 The main differences between the summary heap and stack are as follows: 1. Different management methods; 2. Different space sizes; 3. Whether fragments can be generated; 4. Different Growth directions; 5. Different allocation methods; 6. Different allocation efficiency; Management Methods: For stacks, the compiler automatically manages them without manual control.ProgramStaff control, easy to generate memory leak. 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 stacks, there is usually a certain amount of space. For example, under vc6, the default stack space is 1 MB. Of course, this value can be modified. Fragment problem: for the heap, frequent New/delete operations will inevitably lead to discontinuous memory space, resulting in a large number of fragments.ProgramReduced 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-upContentIt has been popped up. For details, refer to the data structure. 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. The dynamic allocation is implemented by the malloca function, but the dynamic allocation of stacks is different from that of stacks. The 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 will follow certain algorithms (for specific algorithms, refer to the data structure/operating system) in the heapIn MemorySearch 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 increaseProgramData SegmentMemory space.
To a sufficient size of memory, and then return. Obviously, the heap efficiency is much lower than the stack efficiency. Here we can see that the heap and stackPhaseBecause of the use of a large number of new/delete operations, it is easy to cause a large amount of memory fragments; because there is no dedicated system support, the efficiency is very low; because it may lead to switching between the user State and the core state, memory Applications are more expensive. ThereforeProgramIs the most widely used, and 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 advantagesPhaseSometimes it is better to allocate a large amount of memory space than it is not so flexible. Whether it is a heap or a stack, cross-border phenomena should be prevented (unless you intentionally cross-border it), because the cross-border result is eitherProgramCrash, or destroyProgramStack structure, produce unexpected results.4. Comparison between new/delete and malloc/freeFrom the perspective of C ++, using new to allocate heap space can call the class constructor, while the malloc () function is just a function call and does not call the constructor, it accepts an unsigned long parameter. Similarly, delete calls the Destructor before releasing the heap space, while the free function does not.
Class time {public: Time (INT, Int, Int, string );~ Time () {cout </"call time/'s destructor by:/" <name <Endl;} PRIVATE: int hour; int min; int sec; string name ;}; time: Time (int h, int M, int S, string N) {hour = H; min = m; sec = s; name = N; cout </"call time/'s constructor by:/" <name <Endl;} int main () {time * T1; T1 = (time *) malloc (sizeof (time ));
Free (T1); time * t2; t2 = new time (0, 0,/"T2/"); Delete T2; System (/"Pause /"); return exit_success ;}
Result: Call time/'s constructor by: t2call time/'s destructor by: t2 the result shows that using new/delete can call the object constructor and destructor,AndIn the example, a non-default constructor is called. However, when allocating an array of objects on the stack, you can only call the default constructor. You cannot call any other constructor.
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.