Memory allocation for c/c++--programs

Source: Internet
Author: User

C + + program memory allocation

I. Preliminary knowledge-memory allocation of the program

The memory used by a program compiled by C + + is divided into the following sections
1, Stack (stack): by the compiler to voluntarily allocate the release, storage function of the parameters, the value of local variables and so on. It operates in a similar way to a stack in a data structure.
2, heap area (heap): Generally by the program ape allocation release, if the program ape does not release, the program ends may be recycled by the OS. Note that it is different from the heap in the data structure. Distribution method is similar to the list, hehe.


3, Global Zone (Static): 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 the adjacent area. -System release after the program is finished
4, the literal constant area: constant (string) is put here. Released by the system after the program is finished
5, program code area: the binary code that holds the function body.

//Sample program//main.cppintA =0;//Global initialization ZoneChar*P1;//Global uninitialized zoneMain () {intb//Stack CharS[] ="ABC";//Stack Char*P2;//Stack Char*P3 ="123456";//123456\0 in the constant area, p3 on the stack.  Static intc =0。//Global (Static) initialization zoneP1 = (Char*)malloc(Ten); P2 = (Char*)malloc( -);//The area allocated 10 and 20 bytes is in the heap area.  strcpy(P1,"123456");//123456\0 is placed in the constant area. The compiler might optimize it to a place with the "123456" that P3 points to}

Ii. theoretical knowledge of heaps and stacks
2.1 How to apply
Stack: It is assigned by the system on its own initiative. Like what. Declare a local variable int b in the function; The system itself actively in the stack to open up space for B
Heap: Requires the application of the ape himself, and indicates the size. In C, the malloc function such as P1 = (char *) malloc (10);
In C + + with the new operator such as P2 = (char *) malloc (10); But notice that P1, p2 itself is in the stack.
2.2 response of the system after application
Stack: Only the remaining space on the stack is larger than the requested space. The system will provide memory for the program, otherwise the exception prompt stack will be reported overflow.


Heap: First of all should know that the operating system has a record spare memory address of the linked 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 spare node linked list. The space of the node is allocated to the program, and 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 frees up the memory space correctly. Also, because the size of the found heap node is not necessarily exactly equal to the requested size. The system will take its own initiative to put the extra part into the spare chain list again.
2.3 Application Size Limits
Stack: Under Windows, the stack is the data structure that extends to the low address. 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), assuming that the request for more space than the stack of space, will prompt overflow. Therefore, the space available from the stack is small.
Heap: A heap is a data structure that extends to high addresses. is a non-contiguous area of memory. This is because the system is stored with a list of spare memory addresses, which is naturally discontinuous. The traversal direction of the list is the low address to the high address. The size of the heap is limited by the valid virtual memory in the computer system. This shows that the heap is more flexible and larger than the space available.
2.4 Comparison of application efficiency:
The stack is actively assigned by the system itself, faster. But the program ape is uncontrollable.
Heap is the memory allocated by new, the general speed is slower, and easy to produce memory fragmentation, but it is most convenient to use.
In addition, under Windows. The best way is to allocate memory with VirtualAlloc. He's not in the heap. Nor is it that the stack is directly retaining a fast memory in the process's address space, although it is most inconvenient to use. But it's fast, and it's the most flexible.
2.5 storage contents in stacks and stacks
Stack: When a function is called. 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 various parameters of the function, and in most C compilers, the number of references is the stack from right to left. Then a local variable in the function.

Note that static variables are not in the stack. When the function call ends, the local variable is first out of the stack. Then there is the number of references, and the last stack-top pointer points to the most open address, the next instruction in the main function, which the program continues to execute.
Heap: The size of the heap is usually stored on the heap's head with one byte. The detailed contents of the heap have procedural ape arrangements.
2.6 Comparison of access efficiency
Char s1[] = "AAAAAAAAAAAAAAA"; Char *s2 = "BBBBBBBBBBBBBBBBB";
AAAAAAAAAAA are assigned at the time of execution, while BBBBBBBBBBB is determined at compile time; In a later access. The array on the stack is faster than the string that the pointer points to (such as a heap).

Example:
void Main ()
{Char a = 1;
Char c[] = "1234567890";
Char *p = "1234567890";
A = c[1];
A = p[1];
Return
}
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. The other is to read the pointer value into edx, reading the characters based on edx is obviously slow.


2.7 Summary:
The difference between heaps and stacks can be seen in the following analogy:
The use of stacks is like we go to a restaurant, just order (apply), 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 advantages are fast, but the freedom is small.

The use of heaps is like making your own favorite dishes, more troublesome. But it is more in line with one's taste and greater in freedom.
The difference between heap and stack is mainly divided into: the heap and stack of the operating system, as mentioned above. Not much to say.
There are heaps and stacks of data structures that are different concepts. The heap here actually refers to a data structure for the priority queue (which satisfies the heap nature). The 1th element has the highest priority. The stack is actually a mathematical or data structure that satisfies the advanced nature of the post.
Despite the stack, the stack is said to be linked, but they still have very big differences, connected to call only because of historical reasons.

Heap and Stack (stack) are the two basic concepts that are inevitably encountered in C/s + + programming.

First, both concepts can be found in the book that tells the data structure. They are the main data structures, although the stacks are simpler.
These two concepts are not parallel in the detailed C + + programming framework. The study of the underlying machine code can be revealed. The stack is the data structure provided by the machine system, and the heap is provided by the C/S function library.
said in detail. The modern computer (serial execution mechanism), which supports the data structure of the stack directly at the bottom of the code. This body is now. There is a special register to point to the address of the stack, there is a dedicated machine instruction complete data into the stack out of the stack operation. Such mechanisms are characterized by high efficiency, limited data support, and usually integers, pointers. Data types that are directly supported by systems such as floating-point numbers. Other data structures are not directly supported.

Because of this feature of the stack, the use of stacks is very frequent in the program. The call to the sub-program is the direct use of the stack complete. The call instruction of the machine implies that the return address is pushed into the stack and then jumps to the subroutine address, while the RET instruction in the subroutine implicitly pops the return address from the stack and jumps to the operation.

The self-active variable in C/s + + is the example of using the stack directly, which is why when the function returns, the function's own active variable itself fails (because the stack recovers the state before the call).


Unlike stacks, the data structure of a heap is not supported by the system (whether it is a machine system or an operating system), but is provided by a library of functions. The main Malloc/realloc/free function maintains a set of internal heap data structures. When the program uses these functions to obtain new memory space, the function first attempts to find the available memory space from the internal heap, assuming that there is no memory space to use, and tries to use the system callback to dynamically add the memory size of the program data segment. The newly allocated space is first organized into the internal heap and then returned to the caller in the appropriate form.

When the program frees allocated memory space. This memory space is returned to the internal heap structure and may be handled appropriately (for example, with other spare spaces combined into larger spare spaces). To better fit the next memory allocation request.

It's a complex set of dispensing machines.
Buffer pool (cache) that is actually equivalent to a memory allocation. There are several reasons for using this set of mechanisms:
1. System calls may not support random-sized memory allocations.

Some system calls only support a fixed size and multiple memory requests (per page allocation), which can be wasteful for a large number of small memory classifications.


2. System calls to request memory can be costly.

System calls may involve conversion of the user state and kernel mentality.
3. Memory allocations that are not managed are very easy to cause memory fragmentation under the allocation release operation of a large amount of complex memory.


comparison of heaps and stacks
From the above knowledge, the stack is a system-provided function, characterized by high-speed and efficient. The disadvantages are limited, data is inflexible, and the heap is the function provided by the library. Features are flexible and convenient, the data adapt to a wide range, but the efficiency of a certain reduction.

A stack is a system data structure that is unique to a process/thread, and a heap is the internal data structure of a function library. Not necessarily unique.

The memory allocated by different heaps cannot be manipulated logically on each other. The stack space is divided into two kinds: static allocation and dynamic allocation. Static allocation is the completion of the compiler, for example, the allocation of its own active variable (auto). Dynamic allocation is completed by the Alloca function. The dynamic allocation of stacks does not need to be released (self-motivated). There is no release function. For portable programs, the dynamic allocation operation of stacks is not encouraged! The allocation of heap space is always dynamic. Although the entire data space will be released back to the system at the end of the program, accurate memory/release memory matching is essential for good programs

Memory allocation for c/c++--programs

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.