Go to: detailed explanations of the stack, heap, static, text constant, and code areas in the computer

Source: Internet
Author: User
Tags array definition

Turn: http://blog.csdn.net/dotneterbj/article/details/8021200

The memory occupied by a C/C ++ compiled program is divided into the following parts:

1. STACK: the stack zone is automatically allocated and released by the compiler, and stores function parameter values and local variable values. The operation method is similar to the stack in the data structure.

2. Heap-generally assigned and 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. Note that it is different from the heap in the data structure (the heap in the data structure is simulated using arrays). The allocation method is similar to the linked list.

3. Global (static)-the storage of global variables and static variables is put together, and the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. -The system is released after the program ends.

4. Text Constant Area-constant strings are placed here. The program is released by the System

5. program code area-stores the binary code of the function body.

 

Ii. Example Program

This is written by a senior. It is very detailed.

// Main. cpp

Int A = 0; global initialization Zone

Char * P1; uninitialized globally

Main ()

{

Int B; stack

Char s [] = "ABC"; stack

Char * P2; stack

Char * P3 = "123456"; 123456 is in the constant zone, and P3 is on 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 is placed in the constant area, and the compiler may optimize it to the "123456" that P3 points.

}

 

Ii. Theoretical knowledge of heap and stack

2.1 Application Method

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:

The programmer needs to apply and specify the size. In C, the malloc Function

For example, P1 = (char *) malloc (10 );

Use the new operator in C ++

For example, P2 = (char *) malloc (10 );

But note that P1 and P2 are in the stack.

 

2.2

System Response after application

STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.

Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.

2.3 Application size limit

STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. Therefore, the space available from the stack is small.

Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.

 

2.4 comparison of application efficiency:

The stack is automatically allocated by the system, which is faster. But programmers cannot control it.

The heap is the memory allocated by new, which is generally slow and prone to memory fragments. However, it is most convenient to use.

In addition, in windows, the best way is to use virtualalloc to allocate memory. Instead of heap or stack, it is to reserve a fast memory in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.

Storage content in 2.5 heap and stack

STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note that static variables are not included in the stack.

When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.

Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.

2.6 comparison of access efficiency

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.

 

2.7 summary:

The difference between stack and stack can be seen in the following metaphor:

Using Stacks is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it). If you are full, you can leave, without having to worry about the preparation work, such as cutting and washing dishes, as well as the cleaning and tail work such as washing dishes and flushing pots, his advantage is fast, but his degree of freedom is small.

Using heap is like making your favorite dishes. It is troublesome, but it suits your taste and has a high degree of freedom.

1. Memory Allocation:

Heap: Generally, it is assigned and released by the programmer. If the programmer does not release the program, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list. The keywords that may be used are new, malloc, delete, and free.

STACK: the compiler automatically allocates and releases the stack, stores the function parameter values, and values of local variables. The operation method is similar to the stack in the data structure.

2. Application Methods:

Heap: the programmer must apply and specify the size. In C, the malloc function is like p1 = (char *) malloc (10). In C ++, the new operator is used. But note that P1 and P2 are in the stack. Because they can still be considered as local variables.

STACK: automatically allocated 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.

3. system response:

Heap: the operating system has a linked list that records the idle memory address. When the system receives a program application, it traverses the linked list to find the heap node with the first space greater than the requested space, delete the node from the idle node linked list and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.

STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.

4. size limit:

Heap: it refers to the data structure extended to the high address and is a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.

STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This sentence means that the top stack address and the maximum stack capacity are pre-defined by the system. In windows, the stack size is fixed (a constant determined during compilation). If the requested space exceeds the remaining space of the stack, overflow is displayed. Therefore, the space available from the stack is small.

5. Efficiency:

Heap: Memory allocated by new. It is generally slow and prone to memory fragments. However, it is most convenient to use. In addition, in windows, the best way is to use virtualalloc to allocate memory, which is not in the heap, nor in the stack. It is to reserve a fast memory directly in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.

STACK: the stack is automatically allocated by the system, and the speed is fast. But programmers cannot control it.

6. content storage:

Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.

STACK: When a function is called, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement) and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note: static variables are not included in the stack. When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.

7. access efficiency:

Heap: char * S1 = "Hellow word"; determined during compilation;

STACK: Char S1 [] = "Hellow word"; it is assigned a value at runtime. Using arrays is faster than using pointers, because pointers need to be transferred using the edX register in the underlying assembly, and arrays can be directly read on the stack.

 

In C ++, memory is divided into five areas: heap, stack, free storage, global/static storage, and constant storage. Stack is the storage area for variables that are automatically allocated by the compiler when necessary and clear when not needed. The variables are usually local variables and function parameters. Heap is the memory blocks allocated by new. Their release compilers are not controlled and controlled by our applications. 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. 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. 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. Constant storage area, which is a special storage area. It stores constants and cannot be modified (of course, you can modify them by improper means, and there are many methods)

Const

Use of const in C:

Const is a key word in C language. It specifies that a variable cannot be changed. Using const can improve the robustness of the program to a certain extent. In addition, while watching other people's code, you can clearly understand the role of const and help you understand the program of the other party.

Although it sounds very simple, in fact, the use of const is also a subtle place in C language, where is the subtlety? See the following questions.

 

Problem: const variables and constants

Why does the ansi c compiler report an error when I use a const variable to initialize an array like in the following example?

Const int n = 5;

Int A [n];

Answer and analysis:

1) the difference between "constant" and "Read-Only variable" is discussed. Constants must be read-only, for example, 5, "ABC", etc. They must be read-only, because there is no place in the program to store its value, and of course it cannot be modified. The "Read-Only variable" is to open a place in the memory to store its value, but this value is limited by the compiler and cannot be modified. The const keyword in C language is used to restrict a modifier that cannot be changed ). In the above Code, variable N is modified as a read-only variable. Unfortunately, the modification is not a constant. Ansi c requires that the dimension of an array definition must be "constant" and "Read-Only variables" are not allowed.

2) Note: in ansi c, this writing method is incorrect, because the array size should be a constant, while const int N and n are just a variable (constant! = Immutable variables, but in the Standard C ++, this defines a constant, which is correct). In fact, according to the compilation process and memory allocation, this method should have been reasonable, but ansi c imposes restrictions on arrays.

3) So what are constants defined in ansi c? The answer is the enum type and the # define macro, both of which can be used to define constants.

 

Problem: const variable and const content

The following code compiler reports an error. Which statement is wrong?

Typedef char * pstr;

Char string [4] = "ABC ";

Const char * P1 = string;

Const pstr P2 = string;

P1 ++;

P2 ++;

Answer and analysis:

The problem lies in P2 ++.

1) The basic const format: const char m;

The limit m is unchangeable.

2) Replace m and const char * PM in Formula 1;

The limit * PM is unchangeable. Of course PM is variable. Therefore, P1 ++ is correct in the problem.

3) Replace 1 char, const newtype m;

The limit m is immutable, and the charptr in the problem is a new type. Therefore, P2 is immutable in the problem, and P2 ++ is incorrect.

(I have read a method in a book that moves const from left to right until it reaches *. For example, const char * P1 is Char const * P1; const pstr P2 is pstr const P2. Therefore, the const modifier limits its previous type. Therefore, the P1 in const char * P1 is not limited to auto-increment, And the content indicated by P1 is limited to Char and cannot be modified, in const pstr P2, pstr is restricted and cannot be modified. That is, P2 itself cannot be modified because it can be understood as char * const P2, as a whole, pstr is a new type of Alias defined by typedef. Const pstr P2 indicates that the P2 variable with the Data Type limited to char * is read-only, so P2 ++ is incorrect .).

For the usage of typedef reference blog: http://www.cnblogs.com/csyisong/archive/2009/01/09/1372363.html

 

Problem: const variables and string constants

What is the problem with the following code?

Char * P = "I'm hungry! ";

P [0] = 'I ';

Answer and analysis:

The code above may cause invalid memory write operations. The analysis is as follows: "I'm hungry" is essentially a String constant, while constants are often placed in the read-only memory area by the compiler and cannot be written. P initially points to this read-only memory zone, while P [0] = 'I' attempts to write this place, And the compiler certainly won't agree.

Problem: const variable and String constant 2

Is char a [3] = "ABC" Legal? What are the risks of using it?

Answer and analysis:

This is legal in Standard C, but its living environment is very small; it defines an array of 3, initialized as "ABC", note, it does not have the usual string Terminator '\ 0', so this array only looks like a string in C language, but it is not actually, so all functions that process the string, for example, strcpy and printf cannot be used on this fake string.

Question 5: const and pointer

In the type declaration, const is used to modify a constant. There are two ways to write it. So, what are the following statements that use const to limit immutable content? See the method mentioned in the red text above.

1) const is in front

Const int nvalue; // nvalue is const

Const char * Pcontent; // * Pcontent is const, and Pcontent is variable

Const (char *) Pcontent; // Pcontent is const, * Pcontent is variable

Char * const Pcontent; // Pcontent is const, * Pcontent is variable

Const char * const Pcontent; // both Pcontent and * Pcontent are const

2) const is behind and equal to the above statement

Int const nvalue; // nvalue is const

Char const * Pcontent; // * Pcontent is const, and Pcontent is variable

(Char *) const Pcontent; // Pcontent is const, * Pcontent is variable

Char * const Pcontent; // Pcontent is const, * Pcontent is variable

Char const * const Pcontent; // both Pcontent and * Pcontent are const

Answer and analysis:

Using const and pointer together is a common confusion in C language. In actual development, especially when looking at other people's code, it is often difficult to judge the author's intention because of this, the following describes my judgment principles (refer to the methods mentioned above to make them easier to understand ):

Draw a line along the number *. If the const is on the left side of *, the const is used to modify the variable pointed to by the pointer, that is, the pointer points to a constant. If the const is on the right side, const is to modify the pointer itself, that is, the pointer itself is a constant. You can view the actual meaning of the above statement based on this rule, and I believe it will be clear at a glance.

In addition, NOTE: For const (char *); Because char * is a whole, equivalent to a type (such as char), this is to limit the pointer to const.

Du sibo, Yongzhou, Hunan 2012

Go to: detailed explanations of the stack, heap, static, text constant, and code areas in the computer

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.