"Reprint" What variables are stored in the heap memory, what variables are stored in the stack memory

Source: Internet
Author: User

Heap and stack differences (stack and heap)


It is generally thought that in c it is divided into these storage areas
1 stacks-with compiler auto-allocation release
2 heap-typically released by programmers, if the programmer does not release, the program may end up being recycled by the OS
3 Global zones (static zones), global variables and static variables are stored in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another area adjacent. The program ends the release.
4 There is also a special place to put constants. -Program End Release


The variables defined in the function body are usually on the stack, and the allocated memory functions such as malloc, Calloc, realloc, etc. are allocated on the heap. The global amount is defined in the body of all functions, and after the static modifier is placed in the global zone (static zone), the static variable defined in the body of all functions is valid in the file and cannot be extern to another file. The static representation defined in the function body is valid only within the function body. In addition, a string such as "ADGFDF" in the function is stored in a constant area.

Like what:
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 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\0 is placed in the constant area, the compiler may associate it with the "12345" that P3 points to.
6 "optimized into a piece.
}


There is a series of reserved field and pass parameters on the stack when the function is called. The size of the stack is limited, the VC default is 2M. Stack is not enough to use the situation is generally allocated in the program a large number of arrays and recursive function hierarchy too deep. It is important to know that when a function call is finished, it frees all the stack space in the function. Stacks are automatically managed by the compiler, and you don't have to worry about them. The heap is dynamically allocated memory, and you can allocate it with very large memory. However, a memory leak is caused by bad use. and frequently malloc and free generate memory fragmentation (a bit like disk fragmentation), because C allocates dynamic memory when it is looking for matching memory. The stack does not produce fragmentation. Accessing data on the stack is faster than accessing the data on the heap via pointers.


Generally speaking, stacks and stacks are the same, that is, stacks (stack), and heap is the heap.
Stacks are first-in, usually from high-address to low-address growth.


Heap and Stack (stack) are the two basic concepts that are inevitably encountered in C/s + + programming. First of all, these two concepts can be found in the Book of data structure, they are the basic structure, although the stack is simpler. These two concepts are not parallel in a specific C + + programming framework. The study of the underlying machine code reveals that the stack is the data structure provided by the machine system, while the heap is provided by the C/S function library. Specifically, the modern computer (serial execution mechanism) directly supports the data structure of the stack at the bottom of the code. This is reflected in, there is a dedicated register to the address of the stack, there is a dedicated machine instruction to complete the data into the stack out of the stack operation. This mechanism is characterized by high efficiency, limited data support, generally integer, pointer, floating point and other systems directly supported by the data type, does not directly support other data structures. Because of this feature of the stack, the use of stacks is very frequent in the program. The call to the child program is done directly using the stack. The call instruction of the machine implies that the return address is pushed into the stack and then jumps to the subroutine address, while the RET instruction in the subroutine implicitly pops the return address from the stack and jumps to the operation. The automatic variable in C + + is an example of the direct use of the stack, which is why the automatic variable of the function automatically fails when the function returns (because the Yan-shinny is the dark State).


Unlike stacks, the data structure of a heap is not supported by the system (whether it is a machine system or an operating system), but is provided by a library of functions. The basic Malloc/realloc/free function maintains a set of internal heap data structures. When the program uses these functions to obtain new memory space, the function first tries to find the available memory space from the internal heap, if there is no memory space available, then attempts to use the system to dynamically increase the size of the program data segment memory, the newly allocated space is first organized into the internal heap, It is then returned to the caller in the appropriate form. When the program frees the allocated memory space, this memory space is returned to the internal heap structure and may be appropriately processed (such as merging additional free space into a larger free space) to better fit the next memory allocation request. This complex allocation mechanism is actually equivalent to a memory allocation buffer pool (cache), which has several reasons for using this set of mechanisms:

1. System calls may not support memory allocations of any size. Some system calls only support a fixed size and multiple memory requests (per page allocation), which can be wasteful for a large number of small memory classifications.
2. System calls to request memory can be costly. System calls may involve conversion of the user state and kernel mentality.
3. Memory allocations that are not managed can easily cause memory fragmentation under the allocation release operation of a large amount of complex memory.

Comparison of heaps and stacks

From the above knowledge, the stack is the function provided by the system, the characteristics are fast and efficient, the disadvantage is limited, the data is not flexible, and the stack is the function library provides the function, the characteristic is flexible and convenient, the data adapts widely, but the efficiency has certain reduction. A stack is a system data structure that is unique to a process/thread, and a heap is a library internal data structure that is not necessarily unique. Different heap memory cannot operate on each other. The stack space is divided into two kinds: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the automatic variable (auto) assignment. Dynamic allocation is done by the Alloca function. The dynamic allocation of the stack does not have to be released (it is automatic), and there is no release function. For portable programs, the dynamic allocation of stacks is not encouraged! The allocation of heap space is always dynamic, although all data space will be released back to the system at the end of the program, but an accurate memory/release memory match is an essential element of a good program.


Can put a piece of thinking
The heap and stack grow in the opposite direction,
|--------------| Low Address
| Heap |
|--------------|
| | |
| I |
| |
| ^ |
| Stack | High Address
-----------------
So the heap and stack in the computer are often put in a piece of talk


Nod is generally not necessary to do not create dynamically, the most annoying thing to put new out of the authority of the Department of variables, with the practice of immediately delete.

Reason
1. Stack allocation is faster than the heap, only one instruction is required to match all local variables
2. Stack does not show memory fragmentation
3. Good management of Stack objects

Of course, in some cases, you should write that, like
1. Very Large Object
2. Objects need to be constructed or done at a particular time
3. Classes only allow objects to be created dynamically, such as most of the VCL classes
Of course, you can't hide when you have to use a heap object.

What is the role of heap memory and stack memory?

Heap: Random in order
Stack: Advanced back out
The difference between heaps and stacks
I. Preliminary knowledge-memory allocation of the program
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 works like 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\0 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\0 is placed in a constant area, the compiler may 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 size, in C malloc function such as P1 = (char *) malloc (10); in C + + with the new operator such as P2 = (char *) malloc (10); But notice 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 it's fast and 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, while BBBBBBBBBBB is determined at compile time, but in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).
Like what:
#i nclude
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: the use of stacks like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat 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 less freedom. 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.
The difference between heap and stack is mainly divided into:
The operating system stack and stack, as said above, not much to say. There are heaps and stacks of data structures that are different concepts. The heap here actually refers to a data structure of the priority queue (which satisfies the heap nature), the 1th element has the highest priority, and the stack is actually a mathematical or data structure that satisfies the advanced nature of the post. Although stacks, stacks are said to be linked together, but they are still very different, connected to call only because of historical reasons.

"Reprint" What variables are stored in the heap memory, what variables are stored in the stack memory

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.