Heaps Heap and Stack stack

Source: Internet
Author: User

An English name

Heap and stack are two basic concepts that are often encountered in C/s + + programming. Let's take a look at their English expressions:

Heap ――heap

Stack ――stack

Two two levels of understanding from data structures and systems

These two concepts are not parallel in a specific C + + programming framework. Deep down to the assembly level, the stack is the data structure provided by the machine system, and the heap is provided by the C + + function library. These two concepts can be understood from two levels of data structures and systems:

1, from the data structure level understanding, the stack is one kind of advanced after the linear table, as long as conforms to the advanced principle the linear table all is the stack. There is no relationship between the storage (implementation) of sequential storage (sequential stacks) or chained storage (chained stacks). Heap is a two-fork tree, with the largest heap of the smallest heap, sorting algorithm has a common heap sorting.

2, from the system level understanding, the stack is the system for the running program allocation of advanced after the storage area. When learning bootloader, it is known that in the initialization phase of power-up the stack is allocated for each working mode, where the stack is actually referred to as the stack, which is only for historical reasons. When executing a function, the storage unit of a local variable inside the function can be created on the stack (for the CISC schema, the storage unit of the local variable is created on the register), and the storage units are automatically freed at the end of the function execution. A heap is a system-managed global storage space that can be exploited by programs, and dynamic memory allocations are allocated from the heap.

Specifically, the computer (serial execution mechanism) now supports the data structure of the stack directly at the code level. 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. For example, STMFD and LDMFD in arm directives. Because the stack memory allocation operation is built into the processor's instruction set, it is very efficient, but the supported data is limited, it is generally the data type supported directly by the system such as Integer, pointer, floating-point number, and does not directly support other data structures. In CISC, the invocation of a sub-program is done using a stack. The automatic variable in C + + is also an example of using the stack directly, which is why the function's automatic variable fails when the function returns (because the stack restores the state before the call). Under RISC, these are all done through registers. These are left to be elaborated in the second part of the summary.

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/free function maintains a set of internal heap data structures. When the program uses these functions to obtain new memory space, the function first attempts to find the available memory space from the internal heap. If there is no memory space available, an attempt is made to dynamically increase the memory size of the program data segment with a system call, and the newly allocated space is first organized into the internal heap and then returned to the caller in the appropriate form. When the program frees the allocated memory space, this memory space is returned to the memory 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 is used for the following reasons:

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, the system call request memory may be expensive, because this may involve the user state and nuclear mentality conversion.

3. Memory allocations that are not managed can easily cause memory fragmentation under the allocation release operation of a large amount of complex memory.

Summarize:

1, the stack is the system provides the function, the characteristic is the fast high efficiency, the disadvantage is has the limitation, the data is not flexible, but the heap is the function library provides the function, the characteristic is the flexible convenient, the data adapts the wide range, but the efficiency has the certain reduction.

2, the stack is the system data structure, for the process/thread is unique, heap is the function library internal data structure, not necessarily unique, different heap allocation of memory can not interoperate with each other.

3, stack space static allocation and dynamic allocation of two. Static allocations are done by the compiler, such as the automatic variable (auto) assignment. Dynamic allocation is done by the Alloc 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.

Third, refine the analysis from the system level again

The following is a detailed comparison of the heap and stack from the system hierarchy to better understand the two concepts.

1. Application method

Stack: The system is automatically assigned.

Heap: The programmer himself applies, indicating the size.

2. System response after application

Stack: As long as the remaining space on 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 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, and 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. 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.

3, the application size limit

Stack: In arm, stack is pre-set. At start. s, there can be four different stacks: full stack increment, full stack descending, empty stack increment, empty stack descending. The usual is the full stack descending, is the downward (low address) direction of growth. This is easy to understand if you analyze the Stack settings section of bootloader.

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.

4. Comparison of application efficiency

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

Heap: The memory allocated by new, generally slower, and prone to memory fragmentation, but the most convenient to use.

5. Store Content

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 in the right-to-left stack, followed by 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.

6. Comparison of Access efficiency

Stack: Assign value at run time, high access efficiency.

Heap: At compile time, it is determined that access is less efficient than stack.

Because the stack is allocated by the system, more specifically, it is closely related to whether the CPU is a RISC architecture or a CISC architecture. In the two different instruction set architectures, the treatment of memory allocation is significantly different. One of the principles in RISC architecture is to minimize access to memory and replace it with register resolution. So the number of registers is significantly greater than the register of the CISC architecture. The heap is provided by a library of functions, and the relationship with the system is far away.



++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++



The simple can be understood as:

Heap: Is the location of space allocated by functions such as malloc. The address is increased from low to high.

Stack: Is the automatic allocation of variables, as well as some of the space used when the function is called. The address is reduced by a high-to-low.

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 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 you should know that the operating system has a list of idle memory addresses, when the system receives the application of the program,

The list is traversed to find the first heap node that is larger than the requested space, and then the node is removed from the list of idle nodes, and the space of that node is allocated to the program, and for most systems the size of this allocation is recorded at the first address in the memory space, so that The DELETE statement in the code can properly free up this 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 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 refers to edx and then reads the characters according to EdX, which is obviously slow.

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.

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.

Original: http://www.cnblogs.com/SinSay/archive/2008/11/12/1332076.html

(turn) heap and stack stack

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.