C + + memory allocation

Source: Internet
Author: User

First, prepare the knowledge-memory allocation of the program:

The memory used by a program compiled by C + + is divided into the following sections:
1. Stack (stack)-Automatically allocated by the compiler to release, store the function parameter value, local variable value and so on. It operates in a manner similar to a stack in a data structure.
2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the end of the program 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 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

For example:

1 //main.cpp2 intA=0;//Global Initialization Zone3 Char*P1;//Global Uninitialized Zone4 Main ()5 {6    intb//Stack7    Chars[]="ABC";//Stack8    Char*P2;//Stack9    Char*p3="123456";//123456\0 in the constant area, p3 on the stack. Ten    Static intC=0;//Global (Static) initialization zone OneP1 = (Char*) malloc (Ten); AP2 = (Char*) malloc ( -);//areas that are allocated 10 and 20 bytes are in the heap area.  -strcpy (P1,"123456");//123456\0 is placed in a constant area, the compiler may optimize it with the P3 to "123456" as a place.  -}


Ii. theoretical knowledge of heaps and stacks

2.1 How to apply
Stack (stack): Automatically assigned by the system. For example, declare a local variable in the function int b; The system automatically opens up space for B in the stack
Heap (heap): Requires the programmer to apply himself, and indicates the size of the malloc function in C such as p1= (char*) malloc (10);; such as p2= (char*) malloc (10), but note that P1, p2 itself is in the stack. Use the new operator in C + +.
2.2 Post-application system response
Stack: As long as the remaining space on 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: You should first 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, and , 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. Also, 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.
2.3 Request Size limit
Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. Stack top 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.
2.4 Application Efficiency comparison:
Stack: Automatically assigned by the system, faster. But programmers can't control it.
Heap: Is the memory allocated by new, generally slower, and prone to memory fragmentation, but the most convenient to use.

In addition, under Windows, the best way is to use virtual alloc to allocate memory, he is not in the heap, nor in the stack, but directly in the process of the address space to retain a piece of memory, although the most inconvenient to use. But the speed is fast, also the most flexible. VirtualAlloc is a Windows-provided API that is typically used to allocate large chunks of memory. For example, if you want to implement communication between process A and process B through shared memory, you can use this function (which is also a more common case).

2.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 variable in the function.

Amount 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 the programmer.
2.6 Comparison of access efficiency
Char s1[]= "AAAAAAAAAAAAAAA";
Char *s2= "BBBBBBBBBBBBBBBBB";
AAAAAAAAAAA is assigned at run time;
And BBBBBBBBBBB is determined at compile time;
However, 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#include <iostream>2 voidMain ()3 {4 CharA=1;5 Charc[]="1234567890";6 Char*p="1234567890";7A = c[1];8A = p[1];9 return;Ten}


The corresponding assembly code
10:A=C[1];
004010678A4DF1MOVCL,BYTEPTR[EBP-0FH]
0040106a884dfcmovbyteptr[ebp-4],cl
11:A=P[1];
0040106D8B55ECMOVEDX,DWORDPTR[EBP-14H]
004010708A4201MOVAL,BYTEPTR[EDX+1]
004010738845fcmovbyteptr[ebp-4],al
The first reads the elements in the string directly into the register CL, while the second one reads the pointer value into edx, based on

EdX reads the characters, apparently slowly.
2.7 Summary:
The difference between heap and stack can be seen in the following analogy:
Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.
The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.

Iii. distinguishing between char * and Char []

char * Defines a pointer to a string (note: There is no built-in type or class type for the corresponding string in C), and Char [] is the C language used to define the character array (note: The character array is different from the string, and if the character array ends with '/0 ', it can be treated as a string).

Char a[] is assigned at run time, the value is assigned from the static area to the stack of the function, and modifications to it do not cause any problems. Char *a determines at compile time that a points to a value in the static zone and is not assigned to the function stack, so modifying the contents of the pointer produces an error.

Problem Introduction:

One error, same char *c = "abc" and Char c[]= "ABC", the former changes its

The capacity program crashes, and the latter is completely correct.
Program Demo:

#include <iostream>using namespaceStd;main () {Char*C1 ="ABC"; CharC2[] ="ABC"; Char*C3 = (Char*) malloc (3); C3="ABC"; printf ("%d%d%s\n",&c1,c1,c1); printf ("%d%d%s\n",&c2,c2,c2); printf ("%d%d%s\n",&c3,c3,c3);   GetChar ();} 


Run results
2293628 4199056 ABC
2293624 2293624 ABC
2293620 4199056 ABC

Self-Summary:
char *C1 = "abc"; in fact, first in the literal constant area is allocated a piece of "ABC", then assign an address to the stack on the C1 and point to the address, and then change the constant "ABC" will naturally collapse

Char c2[] = "abc", in fact the place where ABC allocates memory is not the same as the above, and can be
4199056
2293624 See, is completely two places, inferred 4199056 is in the constant area, and 2293624 is in the stack area

2293628
2293624
2293620 This output shows that three pointers are allocated to the stack area and are from high address to low address

2293620 4199056 ABC sees that the compiler will C3 optimize the "ABC" to the constant area


Continue thinking:
Code:

#include <iostream>using namespaceStd;main () {Char*C1 ="ABC"; CharC2[] ="ABC"; Char*C3 = (Char*) malloc (3); //*C3 = "abc"//Errorstrcpy (C3,"ABC"); c3[0] ='g'; printf ("%d%d%s\n",&c1,c1,c1); printf ("%d%d%s\n",&c2,c2,c2); printf ("%d%d%s\n",&c3,c3,c3);   GetChar ();} 


Output:
2293628 4199056 ABC
2293624 2293624 ABC
2293620 4012976 GBC
As a comment, the subsequent changes will crash.
Visible strcpy (C3, "ABC"), ABC is assigned in another place, and can be changed.

The C3 pointer itself is above the stack, but pointing to the content is already on the heap.

Iv. different ways to allocate memory in Windows

(1) malloc

The memory allocation function of the C language is used to allocate general memory space, and the memory allocated by the function is not automatically initialized. Use this function if you are programming in C language. In Visual C + +, the malloc function calls the HeapAlloc function.

The memory allocated by malloc is freed by the free function.

(2) New

The implementation of the C + + language, in Visual C + +, by calling HeapAlloc to implement memory allocation, if you use C + + programming, we recommend that you use new for general memory allocation. The system determines whether the object is initialized based on how it is called.

Note: New is actually an operator instead of a function in C + +.

The memory allocated with new is freed by delete/delete[].

(3) VirtualAlloc

PVOID VirtualAlloc (PVOID pvaddress, size_t dwsize, DWORD Fdwallocationtype, DWORD Fdwprotect)

VirtualAlloc is a Windows-provided API that is typically used to allocate large chunks of memory. For example, if you want to implement communication between process A and process B through shared memory, you can use this function (which is also a more common case). Do not use this function to achieve the usual memory allocations. An important feature of this function is that virtual memory space can be reserved for the specified address and size. For example, if you want to allocate memory somewhere 50MB in the address space of the process, pass the parameter 50*1024* ' 1024 = 52428800 to pvaddress and pass the required memory size to dwsize. If the system has a large enough idle area to satisfy the request, the system will book The block area and return the base address of the reserved memory, otherwise null is returned.

Memory allocated with VirtualAlloc needs to be freed using VirtualFree.

(4) HeapAlloc

HeapAlloc is a Windows-provided API that, when the process is initialized, creates a 1M-sized heap in the process's address space, called the default heap, which is the default, and can be modified by the/HEAP connector switch. Users can also create additional heaps through heapcreate, which can be used more efficiently to manage memory, avoid thread synchronization overhead, and quickly release memory. The HeapAlloc is used to allocate a block of memory from the heap and returns the address of the memory block if the allocation succeeds. The HeapAlloc internally determines the specific implementation based on the size of the request and the size of the heap, for example, when large memory space is required, the VirtualAlloc function is automatically allocated space. This function is typically used to allocate memory space of a general size, and some Windows APIs may require that the function be used for memory allocation and passed to API parameters. Note that when allocating large blocks of memory (such as 1M or more) it is best to avoid using heap functions, VirtualAlloc is recommended.

Use HeapFree to release the allocated memory by HeapAlloc.

C + + memory allocation

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.