Reproduced Some problems of memory allocation in C + + by invading and deleting

Source: Internet
Author: User

program allocation in memory (constants, local variables, global variables, program code)

A. In C are divided into these storage areas
1. Stack-the release is automatically assigned by the compiler
2. Heap-usually released by the programmer, if the programmer does not release, the program may end up being recycled by the OS
3. Global zone (Static zone), global variables and static variables are stored in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another area adjacent. -Program End Release
4. There is also a special place where constants are placed. -Program End Release

The variables defined in the function body are usually on the stack, and the allocated memory functions such as malloc, Calloc, realloc, etc. are allocated on the heap. The global amount is defined in the body of all functions, and after the static modifier is placed in the global zone (static zone), the static variable defined in the body of all functions is valid in the file and cannot be extern to another file. The static representation defined in the function body is valid only within the function body. In addition, a string such as "ADGFDF" in the function is stored in a constant area. Like what:

?
//main.cppinta = 0;      // 全局初始化区char*p1;      // 全局未初始化区voidmain(){    intb;            // 栈区    chars[] = "abc"// 栈区    char*p2; // 栈区    char *p3 = "123456"// p3在栈区;   "123456\0" 在常量区,     staticintc =0;      // 全局(静态)初始化区    p1 = (char*)malloc(10);    p2 = (char*)malloc(20); // 分配得来的10和20字节的区域就在堆区     strcpy(p1, "123456");    // "123456\0" 放在常量区,编译器可能会将它与p3所指向的"123456"优化成一个地方。}

Two. In C + +, memory is divided into 5 zones, which are heap, stack, free storage, global/static storage, and constant storage, respectively.
1. Stacks
are the stores of variables that are allocated by the compiler when needed, and that are automatically clear when not needed. The variables inside are usually local variables, function parameters, and so on.
2. Heap, which is the memory blocks allocated by new, their release compiler does not go to the tube, by our application to control, generally a new will correspond to a delete. If the programmer does not release it, the operating system will automatically recycle after the program finishes.
3. The free storage area, which is the memory blocks allocated by malloc, is very similar to the heap, but it ends up living with no.
4. Global/Static storage , global variables and static variables are allocated to the same piece of memory, in the previous C language, the global variables are divided into initialized and uninitialized, in C + + There is no such distinction, they occupy the same chunk of memory.
5. Constant storage , this is a more special piece of storage, they are stored in a constant, not allowed to modify (of course, you have to pass the improper means can also be modified)

Above quoted http://www.cnblogs.com/JCSU/articles/1051579.html

third, heap and stack of theoretical knowledge
How to apply
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: Requires the programmer to apply himself and indicate the size of the malloc function in C
such as P1 = (char *) malloc (10);
Using the new operator in C + +
such as P2 = (char *) malloc (10);

But note that P1, p2 itself is in the stack.

Three.

If the global variable is not initialized, the default is 0, and the compiler does not prompt for "variable uninitialized."VC + + 6.0 compiler compile-time memory allocation model (memory layout)Category: VC learning 2011-04-02 21:00 194 people read reviews (0) favorite reports

VC + + 6.0 compiler compile-time memory allocation model (memory layout)

----reproduced from the network

Division of Memory Area

The memory used by a program compiled by C + + is divided into the following sections:

1), Stack (stack): the compiler (Compiler) automatically allocates the release, storing 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): Usually released by the programmer, 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, assigning

The way is similar to a linked list.

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 full

The local variable and the uninitialized static variable are adjacent to another 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: the binary code that holds the function body.

Second, the test case (source code and disassembly control)

2.1 test Case Source and disassembly comparison

To be able to visually illustrate the memory layout model, take a look at the Win32 Console application code (table 3.1), where bold text (line label is the leftmost row)

is the C source code, the text is not bold (the leftmost line is the address) is the disassembly of the instruction code. It looks messy, but it must be resistant, and the text behind will be based on it.

3.2 Memory layout diagram

For this case, the following illustrations graphically illustrate the 5 large areas of memory mentioned in section 2nd. It is important to note that the starting address for each area in the diagram is not absolute, and the different compilation environments may not be identical, given just a typical example. It is important to note that the address addressing directions for different regions are also different.

3. Application

We will explain some of the phenomena by understanding the case in section 3rd.

3.1. Variable initialization

1) Local variables are assigned to the stack and are not expected if not initialized. At compile time, the compiler throws a C4700 warning error (local variable ' variable name ' used without having been initialized).

The table 4.1 Code tests the case where the local variable is not initialized.

A typical output of this test is:-858993460, at the same time, the compiler throws a warning error.

2) If the global variable is not initialized, the default is 0, and the compiler does not prompt for "variable uninitialized."

The table 4.2 Code tests the situation where the global variable is not initialized.

The output of this test is: 0.

3) Global variables initialized to 0 are the same as uninitialized effects. Please note that the 9th line of code in table 3.1 is

INTINIT_ARRAY_G1[10]={0}; Initializing the global array 1

is equivalent to:

int init_array_g1[10]; Initializing the global array 1

Of course, with caution, we recommend that you initialize a global variable before using it.

3.2 Effect of variable initialization on code space

This section still discusses the issue of variable initialization, but for the sake of attention, we separate it into subsections. Now look at two test cases.

Case 1: Establish WIN32 Console application project, project name: Test1, code as shown in Table 4.3.

Compile to debug version and look at the size of the Test1.exe executable file in the debug directory, typical size is about 184KB (about 0.18MB).

Case 2: Establish WIN32 Console application project, project name: Test2, code as shown in table 4.4.

Compile to debug version and look at the size of the Test2.exe executable file in the Debug directory, typically about 46MB in size.

Two cases the only difference is in the 0 or 1 initialization of the init_array_g1[] array No. 0 element. The resulting executable file size is vastly different.

As stated above, the global variable is initialized to 0 as the uninitialized effect. Therefore, the Test1 case here does not initialize the global variable.

So what is the effect of initializing the global variables on the code space without initialization?

We know that programs that run on von Neumann architecture systems, data and programs are stored together. Therefore, at compile time, the compiler bundles the initialization data of the global variable into the final generated program file, and for the uninitialized global variable it simply assigns (indicates) the storage location and does not bundle a large number of 0 into the program.

Now take a look at the above two cases. Test1 essentially does not initialize the global variable, and the compile-time compiler simply points out the memory location to be used instead of data binding for init_array_g1[. Test2 is different, it initializes init_array_g1[0] to 1, all other elements are initialized to 0, so the compiler will bundle the initialization data of the 10 million elements of the init_array_g1[] array into the final executable file, Causes the compiled file to be very large.

3.3 About heaps and stacks

For historical reasons, we are used to calling stacks and stacks together (stacks), however, here we have to strictly distinguish the concept of heap and stack.

The local variables declared in the routine are allocated in the stack, and the stack size is quite limited (one, two trillion), the large array may make the stack unusable, resulting in a run-time stack Overflow (Overflow) error (Note: not a compiler Error), and the size of the heap depends largely on the system's available memory and the amount of virtual storage. Here are a few examples:

The case 3 code is shown in table 4.5:

Compile the code without a compile-time error. Run-time error occurred while executing (hint STATCK Overflow) because the stack space is not enough.

Case 4, change the case 3 code, the array is positioned as a global variable, as shown in table 4.6:

Compile the code with no compile-time errors or run-time errors. Because the global variables are not allocated in the stack (note: Also not in the heap), how much space can be used depends on the amount of available memory and virtual storage of the system.

There is one more way to solve the problem of case 3: Dynamic request for memory space.

The memory space for a dynamic request is allocated at run time, and once the application succeeds, it is allocated to the heap, so the size is also dependent on the amount of available memory and the virtual storage of the system.

Case 5: Change the case 3 code in another way, as shown in table 4.7.

Case 5 of the memory space in the heap. Another point is different from Case 4: Case 4 of the memory space is allocated in the compiler, and case 5 of the memory space is allocated at run time, it is possible to allocate space.

3.4) address decreasing the way of compiling

Perhaps other materials have described the concept of "address decrement" addressing the allocation of memory, the so-called "address decrement" refers to when the compiler compiles the program, by variable declaration successively, from the allocated memory from the high address to the low address to allocate memory. What do you mean? Let's look at an example first.

Case 6 is a program with a logic error (table 4.7), which may be called a "perverted" program. So how is it BT?

This program does not have a compiler error, but it is a dead loop program. What we want to know is: why is it a dead loop, not something wrong? We can easily explain the memory layout by the above text.

In the 3rd section you can draw the memory layout (4.1, the starting address in the figure is just a typical case).

Note that array[10] is referenced in the program ———— array subscript is out of bounds (the vc++6.0 compiler can check the displayed subscript out of bounds, but does not check for implicit subscript out-of-bounds). The inside of the loop will be called array[10] 1, and from Figure 4.1, array[10] is essentially I, resulting in the final cycle of the program is taken for granted.

Everything becomes clear, we not only explain the problem in the program, but also understand that the "address reduction" is not a mystery, it is originally mentioned in the stack memory area of the address method.

Reproduced Some problems of memory allocation in C + + by invading and deleting

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.