C/C ++ memory allocation method, heap, stack, new/delete/malloc/free.

Source: Internet
Author: User

Memory Allocation Method

There are three memory allocation methods:

[1] allocated from the static storage area. The program has been allocated when it is compiled, and the program exists throughout the entire runtime. 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. When the program runs, it uses malloc or new to apply for any amount of memory. The programmer is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory is determined by the programmer and flexible to use. However, if space is allocated on the stack, the programmer has the responsibility to recycle it. Otherwise, the running program may experience memory leakage, frequent allocation and release of heap space of different sizes will generate fragments in the heap.

2. program memory space

A program divides the memory blocks allocated to the operating system into four areas, as shown in.

Code area (Code area) program memory space

Data Area)

Heap Area)

Stack Area)

The memory occupied by a C/C ++ compiled program is divided into the following parts,

1. Stack is automatically allocated and released by the compiler, and stores the local variables, function parameters, returned data, and return addresses allocated for running the function. The operation method is similar to the stack in the data structure.

2. The heap is generally assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. The allocation method is similar to the linked list.

3. The Global zone (static) Stores global variables, static data, and constants. System release after the program ends

4. The constant string in the text constant area is placed here. The program is released by the system.

5. The program 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; // global initialization Zone

Char * P1; // not initialized globally

Int main (){

Int B; // 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.

}

Comparison Between Stack and stack

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: the programmer must apply for the heap and specify the size. In C, the malloc function is used, and in C ++, the new operator is used.

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.

2. system response after application

STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.

Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program.

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. Application size limit

STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. 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.

4 Comparison of Application Efficiency

The stack is automatically allocated by the system, which is faster. But programmers cannot control it.

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.

5 Storage content in heap and stack

STACK: 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, where the program continues to run.

Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.

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

The first type reads the elements in the string directly into the CL register, while the second type reads the pointer value into EDX and then reads the characters according to edX, which is obviously slow.

7. Summary

The main differences between stack and stack 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 heaps, 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 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.

Fragmentation problem: for the heap, frequent New/delete operations 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 on the stack 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 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, or destroy the program's heap and stack structure to produce unexpected results.

4. Comparison between new/delete and malloc/free

From 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, 0,/"T2 /");

Delete T2;

System (/"Pause /");

Return exit_success;

}

Result:

Call time/'s constructor by: t2

Call time/'s destructor by: t2

From the results, we can see that using new/delete can call the constructor and destructor of the object, and in 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.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/rujielaisusan/archive/2009/09/30/4622197.aspx

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.