C language stack (stack) and heap (heap) of the use of detailed _c language

Source: Internet
Author: User
Tags data structures

First, the preparation of knowledge-Program memory allocation

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

1, stack area (stack)-by the compiler automatically assigned to release, store the function of the parameter values, local variables and other values. The operation is similar to the stack in the data structure.
2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the program at the end may be reclaimed by the OS. Note that it is different from the heap in the data structure, and the distribution is similar to the linked list.
3, Global zone (static area) (static)-the storage of global variables and static variables is placed in a piece, the initialization of global and static variables in a region, uninitialized global variables and uninitialized static variables in another adjacent area. The system is released after the program is finished.
4, literal constant area-the constant string is here. The system is released after the program is finished.
5, program code area-the binary code that holds the function body.

Second, the example procedure

Copy Code code as follows:

Main.cpp
int a=0; Global initialization Area
Char *p1; Global uninitialized Zone
Main ()
{
INTB; stack
Char s[]= "ABC"; Stack
Char *p2; Stack
Char *p3= "123456"; 123456\0 in the constant area, p3 on the stack.
static int c=0;//Global (Static) initialization area
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\0 is placed in a constant area, the compiler may optimize it with P3 to "123456" into a place.
}

Theory knowledge of heap and stack
2.1 Application Methods
Stack
Automatically assigned by the system. For example, declare a local variable int b in a function, and the system automatically opens up space for B in the stack

Heap
Requires the programmer to apply and indicate the size, using 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 application space, the system will provide memory for the program, otherwise it will be reported abnormal stack overflow.
Heap: You should first know that the operating system has a linked list that records free memory addresses, when the system receives the application, it traverses the list, looks for the first heap node that is larger than the requested space, deletes the node from the Free node list, and assigns the node space to the program, and for most systems, The size of this assignment is recorded at the first address in this memory space, so that the DELETE statement in the code can properly release the memory space. In addition, because the size of the found heap node does not necessarily equal the size of the application, the system automatically puts the extra part back into the free list.

2.3 Limit of application size
Stacks: In Windows, stacks are data structures that extend to a low address and are a contiguous area of memory. The address of the top of the stack and the maximum capacity of the stack are predetermined by the system, in Windows, the size of the stack is 2M (also some say 1M, in short, a compile-time constant), if the application space over the stack of remaining space, will prompt overflow. Therefore, the space can be obtained from the stack is small.
Heap: The heap is a data structure that is extended to a high address and is a contiguous area of memory. This is because the system is using a linked list to store the free memory address, nature is discontinuous, and the chain of the list of the traversal direction is from the low address to the high address. The size of the heap is limited by the virtual memory available in the computer system. This shows that the heap to obtain a more flexible space, but also relatively large.

2.4 Comparison of the efficiency of the application:
Stack: Automatically distributed by the system, faster. But programmers are out of control.
Heap: Is the memory allocated by new, the general speed is slower, and easy to produce memory fragments, but the most convenient to use. In addition, in Windows, the best way is to use virtual alloc to allocate memory, he is not in the heap, nor in the stack, but directly in the process of the address space to retain a piece of memory, although the most inconvenient to use. But fast, and most flexible.

2.5 stacks and stacks of stored content
Stacks: When a function is called, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement). Then there are the parameters of the function, in most C compilers, the parameters are pushed from right to left, 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 first goes out of the stack, then the argument, and the last stack pointer points to the address that was first saved, the next instruction in the main function, where the program continues to run.
Heap: The size of the heap is usually stored in a byte at the head of the heap. The specifics of the heap are arranged by the programmer.

2.6 Comparison of access efficiency

Copy Code code as follows:

Char s1[]= "AAAAAAAAAAAAAAA";
Char *s2= "BBBBBBBBBBBBBBBBB";
AAAAAAAAAAA are assigned at run time, while BBBBBBBBBBB are determined at compile time, but in later accesses, the array on the stack is faster than the string that the pointer points to (for example, the heap). Like what:
#include
int main ()
{
Char a=1;
Char c[]= "1234567890";
Char *p= "1234567890";
A = c[1];
A = p[1];
return 1;
}

The corresponding assembly code

Copy Code code as follows:

10:A=C[1];
004010678A4DF1MOVCL,BYTEPTR[EBP-0FH]
0040106a884dfcmovbyteptr[ebp-4],cl
11:A=P[1];
0040106D8B55ECMOVEDX,DWORDPTR[EBP-14H]
004010708A4201MOVAL,BYTEPTR[EDX+1]
004010738845fcmovbyteptr[ebp-4],al

The first reads the elements in the string directly into the register CL, while the second reads the pointer value into the edx and reads the characters according to EdX, which is obviously slow.
2.7 Summary
The difference between stacks and stacks can be seen in the following analogy: using stacks like we eat in restaurants, just order (apply), pay, and eat (use), go after full, do not have to pay attention to cutting vegetables, vegetables, such as preparation and washing dishes, such as cleaning the pot, his advantage is fast, but the degree of freedom is small. The use of the heap is like a do-it-yourself like to eat dishes, more trouble, but more in line with their own taste, and greater 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.