Stack in "reprint" program can read and write data area constant area code area

Source: Internet
Author: User

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

1. Stack (stack)-Automatically allocated by the compiler to release, store 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)-Generally by the programmer assigned to release, 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, the distribution 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 another area adjacent. -System release 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-binary code that holds the function body.

Ii. Examples of procedures

It was written by a predecessor, very detailed

Main.cpp

int a = 0; Global initialization Zone

Char *p1; Global uninitialized Zone

Main ()

{

int b; Stack

Char s[] = "ABC"; Stack

Char *p2; Stack

Char *p3 = "123456"; 123456 in the constant area, p3 on the stack.

static int c = 0; global (static) initialization zone

P1 = (char *) malloc (10);

P2 = (char *) malloc (20);

Areas that are allocated 10 and 20 bytes are in the heap area.

strcpy (P1, "123456"); 123456 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

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.

2.2

Response of the system after application

Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.

Heap: First of all should know that the operating system has a record of the free memory address of the 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 list of idle nodes, and the node's space allocated to the program, in addition, The size of this allocation is recorded at the first address in this memory space, so that the DELETE statement in the code can properly free up the memory space. Also, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.

2.3 Application Size Limits

Stack: Under Windows, the stack is the data structure to the low address extension, which 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), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.

Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.

2.4 Comparison of application efficiency:

The stack is automatically assigned by the system and is faster. But programmers can't control it.

Heap is the memory allocated by new, the general speed is relatively slow, and prone to memory fragmentation, but the most convenient to use.

In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, nor in the stack is directly in the process's address space to keep a fast memory, although the most inconvenient to use. But the speed is fast, also the most flexible.

2.5 Storage contents in stacks and stacks

Stack: In a function call, 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 parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that static variables are not in the stack.

When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.

Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.

2.6 Comparison of access efficiency

Char s1[] = "AAAAAAAAAAAAAAA";

Char *s2 = "BBBBBBBBBBBBBBBBB";

AAAAAAAAAAA is assigned at run time;

And BBBBBBBBBBB is determined at compile time;

However, in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).

Like what:

#include

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, while the second one reads the pointer values into EDX, which is obviously slow to read the characters according to EdX.

2.7 Summary:

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

Use the stack like we go to a restaurant to eat, just order (send application), 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 advantage is fast, but the freedom is small.

The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.

1, memory allocation aspects:

Heap: Typically released by programmers, if the programmer does not release, the program may end up being recycled by the OS. Note that it is different from the heap in the data structure, and the distribution is similar to a linked list. The following keywords may be used: New, malloc, delete, free, and so on.

Stack: The compiler (Compiler) automatically allocates the release, storing the function's parameter value, the value of the local variable, and so on. It operates in a manner similar to a stack in a data structure.

2. Application Method:

Heap: Requires programmers to apply themselves and indicate size. In C, the malloc function such as P1 = (char *) malloc (10); Use the new operator in C + +, but note that P1, p2 itself is in the stack. Because they can still be considered as local variables.

Stack: Automatically assigned by the system. For example, declare a local variable int b in the function, and 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 free memory address, when the system receives the application, it iterates through the list, finds the first heap node that is larger than the requested space, and then removes the node from the list of idle nodes and assigns the node's space to the program, in addition, for most systems, The size of this allocation is recorded at the first address in this memory space, so that the DELETE statement in the code can properly free up the memory space. In addition, because the size of the found heap node does not necessarily equal the size of the application, the system will automatically re-put the extra portion into the idle list.

Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.

4. Size limitation:

Heap: Is the data structure that extends to the high address, which is a discontinuous memory area. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.

Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack address and the maximum capacity of the stack is the system pre-defined, under Windows, the size of the stack is fixed (is a compile-time determination of the constant), if the requested space exceeds the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.

5, Efficiency aspects:

Heap: Is the memory allocated by new, generally slow, and easy to produce memory fragmentation, but the most convenient to use, in addition, in Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, nor is the stack is directly in the process of the address space to retain a fast memory, Although it is most inconvenient to use. But the speed is fast, also the most flexible.

Stack: Automatically allocated by the system, faster. But programmers can't control it.

6, storage content aspects:

Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.

stack: The first stack in a function call is the address of the next instruction in the main function (the next executable statement of the function call statement) and then the parameters of the function, in most C compilers, the arguments are left-to-right and then local variables in the function. Note: Static variables are not in the stack. When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.

7, Access efficiency aspects:

Heap:char *s1 = "Hellow Word"; it is determined at compile time;

Stack:char s1[] = "Hellow Word"; it is assigned at run time; it is faster to use an array than a pointer, because the pointer needs to be brokered in the underlying assembly with the EDX register, and the array is read directly on the stack.

In C + +, memory is divided into 5 extents, namely heap, stack, free storage, global/static storage, and constant storage. Stacks are 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. 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. 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. Global/static storage, global variables and static variables are allocated in 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 piece of memory area together. Constant storage, which is a special piece of storage, they are stored in constant, not allowed to modify (of course, you have to pass the improper means can also be modified, and many methods)

CONST

Use of const in C:

Const is a C-language keyword that restricts a variable from being allowed to be changed. The use of const to some extent can improve the robustness of the program, in addition, when watching other people's code, clearly understand the role of Const, to understand the other side of the program also has some help.

Although this sounds simple, in fact, the use of const is a more subtle part of C language, where is the subtlety? Here are some questions to consider.

Problem: const variables and constants

Why do I initialize an array with a const variable as in the example below, and the ANSI C compiler will report an error?

const int n = 5;

int a[n];

Answers and Analysis:

1), this question discusses the difference between "constant" and "read-only variable". Constants are definitely read-only, such as 5, "ABC", etc., is definitely read-only, because there is no place in the program to store its value, of course, it is not able to modify it. A "read-only variable" is a place in memory to store its value, except that the value is not allowed to be modified by the compiler. The C keyword const is a modifier (Qualifier) that defines a variable that is not allowed to be changed. In the above code, the variable n is decorated as a read-only variable, but how to modify it is not a constant. While ANSI C specifies that the dimension must be "constant" when defining an array, "read-only variables" are not allowed.

2), note: In ANSI C, this notation is wrong, because the size of the array should be a constant, and the const int n,n is just a variable ( constant! = immutable variable, but in standard C + + , this defines a constant, This kind of writing is true, in fact, according to the compilation process and memory allocation, this usage should be reasonable, but the ANSI C logarithm of the set limit it.

3), so, what do you use to define constants in the ANSI C language? The answer is an enum type and a # define macro, both of which can be used to define constants.

Problem: const variables and const-qualified content

The following code compiler will report an error, excuse me, which statement is wrong?

typedef char * PSTR;

Char string[4] = "ABC";

const char *P1 = string;

Const PSTR P2 = string;

p1++;

p2++;

Answers and Analysis:

The problem is on the p2++.

1), the basic form of const use: const char m;

Limit m immutable.

2), replace M in 1, const char *PM;

Limited *pm immutable, of course PM is variable, so the problem is p1++ is right.

3), replace 1 char, const newType m;

The charptr in the problem is a new type, so the P2 of the problem is immutable and the p2++ is wrong.

Problem: const variables and string constants

What is the problem with the following code?

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

p[0]= ' I ';

Answers and Analysis:

The above code may cause an illegal write operation to the memory. The analysis follows, "I m hungry" is essentially a string constant, and constants are often placed in a read-only memory area by the compiler and are not writable. P initially points to this read-only memory area, while p[0] = ' I ' attempts to write this place, and the compiler will of course not agree.

Problem: const variable & string constant 2

does char a[3] = "abc" legal? What is the danger of using it?

Answers and Analysis:

In standard C This is legal, but its living environment is very small; it defines an array of size 3, initialized to "abc",note that it does not have the usual string terminator ' \ n ', So this array just looks like a string in C, but it's not, so all the functions that handle strings, such as strcpy, printf, and so on , cannot be used on this pseudo-string.

Question 5:const & pointers

In a type declaration, a const is used to modify a constant, as in the next two ways, so, what is the immutable content of a const qualifier below?

1), const in front

const int Nvalue;//nvalue is const

const char *pcontent; *pcontent is const, pcontent variable

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

char* Const pcontent; Pcontent is const, *pcontent variable

const char* Const pcontent; Pcontent and *pcontent are both const.

2), const in the back, with the above declaration peering

int const nvalue;//Nvalue is const

Char Const * pcontent;//*pcontent is const, pcontent variable

(char *) const pcontent;//pcontent is const, *pcontent variable

char* Const pcontent;//pcontent is const, *pcontent variable

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

Answers and Analysis:

The use of const and pointers is a common confusion in C language, in the actual development, especially when looking at other people's code, often because of this rather than judge the author's intentions, the following is my judgment principle:

Line along the * number, if the const is on the left side of the * , then the const is used to decorate the variable pointed to by the pointer, that is, the pointer to a constant, if the const is located in the * on the right,const is the modifier pointer itself, that is, the pointer itself is a constant. According to this rule you can see the actual meaning of the above statement, I believe it will be at a glance.

In addition, it is important to note that for const (char *); Because char * is a whole, equivalent to a type (such as char), this is a qualified pointer that is const.

Stack in "reprint" program can read and write data area constant area code area

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.