C ++ Memory Address Allocation and memory partition details, Address Allocation details

Source: Internet
Author: User

C ++ Memory Address Allocation and memory partition details, Address Allocation details
Introduction to memory types in C ++ Memory Address Allocation and memory Partition

Kernel: in some systems, when a system call occurs, the operating system or the operating system kernel program part of the application memory.

STACK: the stack contains activity records, including the return address of the current function call and local variables.

Shared Library: A memory segment created to dynamically link shared library files

Heap memory: a block of memory used and allocated by the heap memory. If some small memory blocks of variable size are required during the runtime, the memory is allocated from this region.

Uninitialized data: uninitialized global variables are placed in a fixed address. Generally, this region is initialized to 0.

Initialized data: any data that has been assigned an initial value is organized in a contiguous area of the memory, so they can be effectively loaded together with the program page.

Program page: The machine code command that constitutes the application is the program page. When hardware is supported, the program page is usually read-only, which can prevent the program from accidentally overwriting its own command area.

0th page: normally, a memory segment starting with address 0 is retained and set to an unreadable area, which can be used to catch a common error, this error occurs when a NULL pointer is used to access data.

Part 1 Introduction to C ++ Memory Address Allocation

1. The memory address is allocated from the high address to the low address:

int i=1;  int j=1;  cout

2. The storage method of the function parameter list is to allocate an address to the rightmost parameters and then to the leftmost parameters.

3 In Little-endian mode, the number of CPU operations is stored from low bytes to high bytes.

0x1234 storage method:

0X4000 0x34

0X4001 0x12

4. The Big-endian mode stores the number of CPUs in bytes from high to low.

0x1234 storage method:

0x4000 0x12

0x4001 0x34

5 The order in which union members are stored is that all members are stored from low addresses.

6. The address of a variable is represented by the memory space occupied by the variable.

0X4000 0x34

0X4001 0x12

0x1234 address bits 0x4000

7 The stack is allocated from the high memory address to the low memory address.

Int ivar = 0;

Int iarray [2] = {11, 22 };

Note that iarray [2] is out-of-bounds, for example, assigning a value to it

Iarray [2] = 0;

Then, the value of ivar is 0 at the same time, which may lead to an infinite loop, because they have the same address, that is, & ivar is equal to & iarray [2].

Part 2 division of C/C ++ memory

I. In C, it is divided into these storage areas.

1. the stack is automatically allocated and released by the compiler;

2. the stack is generally distributed and released by the programmer. If the programmer does not release the stack, 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. The program ends and is released.

The variables defined in the function body are usually on the stack. The memory allocated by using malloc, calloc, realloc, and other functions is 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, strings such as "adgfdf" in the function are stored in the constant area. For example:

Int a = 0; // global initialization zone char * p1; // void main () {int B; // stack char s [] = "abc "; // stack char * p2; // stack char * p3 = "123456"; // 123456 {post. content} in the constant area, p3 static int c = 0 on the stack; // global (static) initialization area p1 = (char *) malloc (10 ); // The allocated 10-byte area is in the heap area p2 = (char *) malloc (20); // The allocated 20-byte area is 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

They are 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, which is a special storage area. It stores constants and cannot be modified (you can also modify them by improper means ).

On bbs, the distinction between stack and stack seems to be an eternal topic.

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 block of stack memory, so this sentence means that the stack memory stores a pointer p pointing to a block of heap memory.

The program will first determine the size of memory allocated in the heap, then call operator new to allocate the memory, then return the first address of the memory, and put it into the stack, the assembly code in VC6 is as follows:

00401028 push 14 h 0040102A call operator new (00401060) 0040102F add esp, 4 00401032 mov dword ptr [ebp-8], eax 'write code piece here '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? If it is wrong, it should be delete [] p to tell the compiler: I deleted an array and VC6 will release the memory according to 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.

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 it is popped up, the stack content that comes in after it has been popped up. For details, refer to the data structure. Here we will not discuss it one by one.

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. Dynamic Allocation is implemented by the alloca function, but the dynamic allocation of stacks is different from that of stacks. The dynamic allocation of stacks is released by the compiler and does not need to be implemented manually.

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 (my Note: For details about the EBP register, refer to another article ).

The heap is provided by the C/C ++ function library, and its mechanism is very complicated. For example, to allocate a piece of memory, the library function follows certain algorithms.

(For specific algorithms, refer to the data structure/operating system) Search for available enough space in the heap memory. If not

(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, either it is to destroy the heap and stack structure of the program to produce unexpected results. Even if the above problem does not occur during your program running, you should be careful, maybe it will collapse at any time, at that time, debug was quite difficult :)

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.