Stack problems to solve the problem of stack imbalance

Source: Internet
Author: User

Stack problems to solve the problem of stack imbalance

One of the two classes in C ++ can only allocate space in the stack, and one can only be allocated in the heap.

Answer: (1) the code is as follows:
# Include <iostream> using namespace std; // only memory class HeapOnly {public: HeapOnly () {cout <"Construct. "<endl;} void destory () {delete this;} private :~ HeapOnly () {}}; // only space class StackOnly {public: StackOnly () {}~ can be allocated on the stack (){}~ StackOnly () {} private: void * operator new (size_t size) // privatize the new operator. It cannot be called outside {}}; int main () {HeapOnly * hO = new HeapOnly (); hO-> destory (); // HeapOnly he; // compilation error: HeapOnly ::~ HeapOnly ": the private member cannot be accessed (declared in the" HeapOnly "class), so the space StackOnly so of this object cannot be allocated through stacks; // StackOnly * st = new StackOnly (); // StackOnly: operator new ": unable to access private members (declared in the" StackOnly "class )}
(2) Introduction to stack memory allocation

1. The memory occupied by a compiled C/C ++ program is divided into the following parts:
1. stack: the stack is automatically allocated and released by the compiler, and stores function parameter values and local variable values. Even the function call process is completed by stack. The operation method is similar to the stack in the data structure.
2. heap: Generally, it is manually applied 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 allocation method is similar to the linked list.
3. Global (static): stores global variables and static variables. initialized global variables and static variables are stored in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. After the program ends, the system releases the space.
4. Text Constant Area: constant strings are placed here. After the program ends, the system releases the space.
5. program code area: stores the binary code of the function body.

The following example shows the memory regions occupied by different variables:

// Main. cppint a = 0; global initialization zone char * p1; Global uninitialized Zone main () {int B; // stack char s [] = "abc "; // char * p2 in the stack; // char * p3 = "123456" in the stack; // 123456/0 in the constant zone, and p3 in the stack static int c = 0; // The Global (static) initialization zone // The following 10 and 20 bytes are allocated in the heap zone p1 = (char *) malloc (10 ); p2 = new char [20]; // (char *) malloc (20); strcpy (p1, "123456"); // put 123456/0 in the constant area, the compiler may optimize it to the "123456" that p3 points .}

 

Ii. stack and heap.

1. In terms of Application Method
Stack: Many people now call it a stack, which is actually a stack. It is automatically managed by the compiler without manual control. For example, when declaring a local variable in a function, the int B system automatically opens up space for B in the stack. When calling a function, the system automatically opens space for the function's parameter variables in the stack.
Heap: the application and release are controlled by the programmer and the size is specified. Memory leak is easy to generate.
Use the malloc function in C.
For example, p1 = (char *) malloc (10 );
Use the new operator in C ++.
For example, p2 = new char [20]; // (char *) malloc (10 );
However, note that p1 is in the global zone, while p2 is in the stack, but the space they point to is in the heap.

2. system response after application
Stack: as long as the remaining space of the stack is larger than the requested 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 the idle memory address. When the system receives the 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. In this way, the delete or free 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.

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. For example, under VC6, the default stack space is 1 MB (as if it was, but it is hard to remember ). Of course, we can modify it: Open the Project and choose Project> Setting> Link from the following menu. Select Output in Category and set the maximum value and commit of the stack in Reserve.
Note:: The minimum reserve value is 4 bytes. commit is stored in the page file of the virtual memory. It sets a larger value for Stack opening, which may increase the memory overhead and startup time.

Heap: the heap is a data structure extended to the high address and a non-sequential memory area (the idle part is connected in a linked list ). Because the system uses a linked list to store idle memory, it is naturally not continuous, and the traversal direction of the linked list is from low address to high address. 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. It can be seen that the space obtained by the heap is flexible and large.

4. space allocation efficiency
Stack: the stack is the data structure provided by the machine system. 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. But programmers cannot control it.
Heap: the memory allocated by new or malloc is provided by the C/C ++ function library, which is generally slow and prone to memory fragments. Its mechanism is very complicated. For example, in order to allocate a piece of memory, the library function will follow certain algorithms (for specific algorithms, refer to the data structure/operating system) 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, so that there is a chance to allocate enough memory and then return. This may lead to switching between the user State and the core state, and the memory application will become more expensive. Obviously, the heap efficiency is much lower than the stack efficiency.

5. Storage content in heap and stack
Stack: when calling a function, the first entry to the stack is the address of the next instruction (the next executable statement of the subfunction CALL statement) after the subfunction is called, then the parameters of the sub-function. In most C compilers, parameters are written from right to left into the stack, followed by local variables in subfunctions. Note: static variables are not included in the stack. When the function call ends, the local variables first go out of the stack, then the parameters, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction of the main function subfunction call, the program continues to run at this point.
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.

6. Comparison of access efficiency
This should be obvious. Take the array on the stack and the array on the stack for example:

void main(){       int arr[5]={1,2,3,4,5};       int *arr1;       arr1=new int[5];       for (int j=0;j<=4;j++)   {   arr1[j]=j+6;   }      int a=arr[1];       int b=arr1[1];}

In the code above, arr1 (local variable) is in the stack, but the space to be pointed to is indeed on the stack. The access efficiency of both is of course high for arr. Because arr [1] can be accessed directly, but to access arr1 [1], you must first access the starting address of the array arr1 before accessing arr1 [1].

All in all:
The difference between stack and stack can be seen in the following metaphor:
Using Stacks is like eating at a restaurant, just ordering (declaring variables), paying, and eating (using), and leaving when we're full, 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.

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.