C/C ++ memory zone allocation

Source: Internet
Author: User

I. In C, there are several storage areas
1. Stack-automatically assigned and released by a compiler
2. Heap-generally 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.
3. in the global zone (static zone), global variables and static variables are stored in one partition, and initialized global variables and static variables are stored in one partition, uninitialized global variables and uninitialized static variables are in another adjacent area. -Release after the program ends
4. There is also a special place to place constants. -Release after the program ends

In
The variables defined in the function body are usually on the stack, using malloc, calloc,
Realloc and other memory allocation functions are allocated on the stack. All functions define a global volume in vitro. After the static modifier is added, all functions are stored in the global zone (static zone) no matter where they are located.

Static variables defined by all functions in vitro are valid in this file and cannot be used in other files. Static variables defined in the function body are valid only in this function. In addition
The string "adgfdf" in the number is stored in the constant area. For example:
Code:
Int A = 0; // global initialization Zone
Char * P1; // not initialized globally
Main ()
{
Int B; // Stack
Char s [] = "ABC"; // Stack
Char * P2; // Stack
Char * P3 = "123456"; // 123456 {post. Content} is in the constant area, and P3 is in the stack.
Static int C = 0; // global (static) initialization Zone
P1 = (char *) malloc (10 );
P2 = (char *) malloc (20 );
// The allocated 10-byte and 20-byte areas are in the heap area.
Strcpy (P1, "123456 ");
// 123456 {post. Content} is placed in the constant area, and the compiler may optimize it with "123456" pointed to by P3.
}
2. In C ++, the memory is divided into five areas: heap, stack, free storage, global/static storage, and constant storage.
1. Stack is the storage area for variables allocated by the compiler when needed and automatically identified when not needed. The variables are usually local variables and function parameters.
2. Heap refers to the memory blocks allocated by new. Their release compiler is not controlled and controlled by our application. Generally, a new compiler corresponds to a Delete. If the programmer does not release the program, the operating system will automatically recycle it after the program is completed.
3. The free storage zone is the memory blocks allocated by malloc and so on. It is very similar to the heap, but it uses free to end its own life.
4. in the global/static storage area, global variables and static variables are allocated to the same memory. In the previous C language, global variables were divided into initialized and uninitialized ones, in C ++, there is no such distinction. They share the same memory zone.
5. Constant storage area. This is a special storage area where constants are stored and cannot be modified. (Of course, you can modify them by improper means)
Now let's talk about the relationship and difference between stack and stack:
With
Specifically, modern computers (serial execution mechanisms) directly support the stack data structure at the bottom of the Code. This is reflected in the fact that there are dedicated registers pointing to the address of the stack, and dedicated machine commands to complete data import and export into the stack
Stack operations. This mechanism is characterized by high efficiency and limited data types supported by systems such as integers, pointers, and floating point numbers. It does not directly support other data structures. Because the stack
This feature features frequent use of stacks in programs. The call to the subroutine is done directly using the stack. The call command of the machine implicitly pushes the return address into the stack, and then jumps to the Child Program.
The RET command in the subroutine hides the operation that returns the address and jumps from the stack. The automatic variables in C/C ++ use the stack directly.
The reason that the automatic variable of the function is automatically invalid when the function returns.

Unlike the stack, the stack data structure is not supported by the system (whether the machine system or the operating system), but by the function
Library. Basic malloc/realloc/free
The function maintains an internal heap data structure. When the program uses these functions to obtain new memory space, this function first tries to find available memory space from the internal heap.
Memory space, the system calls are used to dynamically increase the memory size of the program data segment. The newly allocated space is first organized into the internal heap, and then return it to the caller in the appropriate form. Dangcheng
When the allocated memory space is released sequentially, this memory space is returned to the internal Heap Structure and may be properly processed (for example, merged into a larger idle space with other idle space ), to better suit the next memory
Allocate application. This complex allocation mechanism is actually equivalent to a buffer pool (cache) for memory allocation. There are several reasons for using this mechanism:
1. system calls may not support memory allocation of any size. Some system calls only support fixed memory requests and their multiples (allocated by PAGE). This will cause a waste for a large number of small memory categories.
2. System Call memory application may be expensive. System calls may involve switching between user and core states.
3. Unmanaged memory allocation can easily cause memory fragmentation when a large amount of complex memory is allocated and released.

Stack and stack comparison:
Slave
According to the above knowledge, stack is the function provided by the system, which is fast and efficient. Its disadvantage is its limitation and data is not flexible. Stack is the function provided by the function library, which is flexible and convenient, wide range of data adaptation, but with a high efficiency
Reduce. The stack is the system data structure, which is unique for processes/Threads. The heap is the internal data structure of the function library, which is not necessarily unique. Memory allocated by different heaps cannot be operated on each other. Static stack space allocation
And dynamic allocation. Static allocation is completed by the compiler, such as automatic variable allocation. Dynamic Allocation is completed by the alloca function. Stack dynamic allocation does not need to be released (it is automatic), so no
There are release functions. For the sake of portable programs, dynamic stack allocation is not encouraged! Heap space allocation is always dynamic. Although all data spaces are released back to the system at the end of the program
Precise memory application/memory release matching is the basic element of a good program.


1. fragmentation problem: for the heap, frequent New/delete operations will inevitably lead to memory space disconnections, resulting in a large number of fragments and reduced program efficiency. This question does not exist for stacks.

Because the stack is an advanced and backward 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, the stack content that follows him has been popped up. For details
For details, refer to the data structure. Here we will not discuss it one by one.
2. 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.
3. 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. Dynamic Allocation is implemented by the alloca function, but the stack dynamic allocation is different from the heap dynamic allocation. Its Dynamic Allocation is released by the compiler without manual implementation.

4. 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 effect of the stack.

High rate. 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 follow certain algorithms (for specific algorithms, refer to data structures/operating systems)
Search for available enough space in the heap memory. 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.
In this case, you have the opportunity to allocate more memory to a sufficient size and then return it. Obviously, the heap efficiency is much lower than the stack efficiency.

Clearly differentiate stack and stack:
On the BBS, the distinction between heap and stack seems to be an eternal topic. It can be seen that beginners are often confused about this, so I decided to take him first.
First, let's take an example:
Void F () {int * P = new int [5];}

This short sentence contains the heap and stack. When we see new, we should first think that we allocated a heap memory. What about the pointer P? It allocates a stack of memory, so the meaning of this sentence is:
A pointer P pointing to a heap memory is stored in the stack memory. The program will first determine the size of memory allocated in the heap, and then call operator
New allocates memory, then returns the first address of the memory, and puts it into the stack. The Assembly Code under vc6 is as follows:
00401028 push 14 h
0040102a call operator new (00401060)
0040102f add ESP, 4
00401032 mov dword ptr [ebp-8], eax
00401035 mov eax, dword ptr [ebp-8]
00401038 mov dword ptr [ebp-4], eax
Here, we have not released the memory for simplicity, So how should we release it? Is it delete p? Australia, the error should be "Delete [] P" to tell the compiler: I deleted an array and vc6 will release the memory based on the cookie information.
Well, let's go back to our topic: What is the difference between stack and stack?
The main differences 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 the stack, there is usually a certain amount of space. For example, under vc6, the default stack space is 1 MB (as if so, I cannot remember ). Of course, we can modify:
Open the project and choose Project> setting> link, select output from category, and set the maximum value and commit of the stack in reserve.
Note: The minimum reserve value is 4 byte. Commit is retained in the page file of the virtual memory. Compared with the general setting, commit makes the stack open up a large value, memory overhead and startup time may be increased.

Compared with the stack, the use of a large number of new/delete operations may easily cause a large amount of memory fragments. Due to the absence of dedicated system support, the efficiency is very low; because it may lead to switching between user and core states, the memory

The application cost becomes more expensive. Therefore, stacks are the most widely used in applications. Even function calls are completed using stacks. parameters, return addresses, EBP, and local variables in function calls use stacks.
. Therefore, we recommend that you use stacks instead of stacks.

Comparison of access efficiency:
Code:
Char S1 [] = "aaaaaaaaaaaaa ";
Char * S2 = "bbbbbbbbbbbbbbbbb ";
Aaaaaaaaaaa is assigned a value at the runtime;
Bbbbbbbbbbbbb is determined during 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:
# Include
Void main ()
{
Char A = 1;
Char C [] = "1234567890 ";
Char * P = "1234567890 ";
A = C [1];
A = P [1];
Return;
}
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. Reading the characters based on edX is obviously slow.

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, either it is to destroy the heap and stack structure of the program and generate unexpected results.
When your program runs, the above problem does not occur. You should be careful. Maybe it will crash at any time. Writing stable and secure code is the most important thing :)

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.