Stack and stack differences

Source: Internet
Author: User

Reprinted Source: http://blog.csdn.net/yuliu0552/article/details/6703505

I. prerequisites-program memory allocation

The memory occupied by a C/C ++ compiled program is divided into the following parts:
1,Stack): The Compiler automatically assigns release, stores function parameter values, local variable values, and so on. Its
The operation method is similar to the stack in the data structure.
2,Heap): Generally, it is assigned to the programmer for release. If the programmer does not release the program, it may be recycled by the OS at the end of the program. Note:It is different from the heap in the data structure.The allocation method is similar to the linked list.
3,Global zone (static zone)(Static): the storage of global variables and static variables is put in one area, 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 program is released by the system.
4,Text Constant Area: Constant string is placed here. The program is released by the System
5,Code Area: Stores the binary code of the function body.

Ii. Example Program
This is written by a senior. It is very detailed.

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/0 is in the constant zone, and P3 is in 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/0 is placed in the constant area, the compiler may optimize it to the "123456" that P3 points. }

Ii. Theoretical knowledge of heap and stack
Application Method
STACK:
Automatically assigned by the system. For example, declare a local variable int B in the function; the system automatically opens an empty room for B in the stack.
Heap:
The programmer must apply and specify the size.Malloc in CFunction
For example, P1 = (char *) malloc (10 );
InUse new in C ++Operator
For example, P2 = new char [10];
But note:P1 and P2 are in the stack..

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 hasLinked List that records idle memory addressesWhen the system receives the applicationTraverse the linked listFind the heap node with the first space greater than the requested space, and thenDelete the node from the idle node linked listAnd allocate the space of the node to the program. In addition, for most systemsRecord the allocation size at the first addressIn this way, 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 automaticallyAdd the excess parts to the idle linked list..


Application size limit
STACK: in WindowsStack is the data structure extended to the low address, YesA contiguous area of memory. This sentence meansThe stack top address and the maximum stack capacity are pre-defined by the system.In Windows, the stack size is 2 m (OR 1 m, which is a constant determined during compilation ), if the requested space exceeds the remaining space of the stack, overflow is displayed. Therefore,Small space available from Stack.
Heap:The heap is a data structure extended to the high address., YesDiscontinuous memory areas. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, and the linked listThe traversal direction is from low address to high address. HeapThe size is limited by the valid virtual memory.. As you can see,The space obtained by the heap is flexible and large..


Comparison of application efficiency:
 StackAutomatically assigned by the system,Fast. But programmers cannot control it.
HeapMemory allocated by new, generallySlow speedAnd easily generate memory fragments, but it is most convenient to use.
In Windows, the best way is to use virtualalloc to allocate memory. Instead of heap or stack, it is to reserve a piece of memory directly in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.


Storage content in heap and stack
STACK: when calling a function, the first entry to the stack is the next instruction in the main function (The next executable statement of the function call statement.), And thenFunction ParametersIn most C compilers, parameters are written from right to left into the stack, and thenLocal 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: usually in the heapThe header stores the heap size in one byte.. The specific content in the heap is arranged by the programmer.

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 accessThe array on the stack is faster than the string pointed to by the pointer (such as the heap )..
For example:

void main()      {      char a = 1;          char c[] = "1234567890";          char *p ="1234567890";          a = c[1];          a = p[1];          return;      }  

The first type reads the elements in the string directly into the CL register, while the second type reads the pointer value into EDX and then reads the characters according to edX, which is obviously slow.

2.7 summary:
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.

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.