Detailed comparison of the difference between heap and stack

The difference between heap and stack

The difference between heap and stack we need to compare the direction of the data structure and the memory direction of the virtual machine from two aspects. The stack mentioned in the two places has two different meanings.

Data structure direction

Heap and stack are both a data structure in which data items are arranged in order, both of which are used to store temporary data

  1. The stack is a linear structure LIFO, and only delete (pop) or insert (pop) operations on the top of the stack are allowed.
  2. A pile generally refers to a two-pronged pile, which can be viewed as a tree. The root node of the heap is the maximum or minimum value, and the addition or deletion is arbitrary. Often used for heap sort. The custom memory variables such as new and malloc are stored in the memory.
  3. The queue is first in, first out, delete operation at the head of the queue, and insert operation at the end of the queue.

Virtual machine memory direction

Generally, the program is stored in Rom or Flash, and needs to be copied to the memory for execution during operation, and the memory will store different information respectively. The data allocation address in the memory is as follows:

  1. Stack area (stack): automatically allocated and released by the compiler, storing function parameter values, local variable values, etc. Its operation is similar to the stack in the data structure.

  2. Heap: Generally allocated and released by the programmer, if the programmer does not release, it may be reclaimed by the OS when the program ends. Note that it is different from the heap in the data structure, and the allocation method is similar to a linked list, ha ha.

  3. Global area (static static area): The storage of global variables and static variables are placed together, initialized global variables and static variables are in one area, and uninitialized global variables and uninitialized static variables are in another adjacent area .
    The static area is a readable and writable memory space. This space is the address of the compiled space where you write the program (determined by the compiler) and is fixed. -System release after the program ends

  4. Text constant area: The constant string is placed here. Released by the system after the program ends

  5. Program code area: store the binary code of the function body.

Create and destroy

1) Stack : It is automatically allocated and released by the operating system. It creates storage space when the operating system establishes a certain process or thread. The required Stack size can be specified during compilation.
The stack is generally at a higher address bit, and the stack address increases downward. When exiting the function, just modify the stack pointer to destroy the contents of the stack, so the speed is the fastest.

The function parameter values ​​and local variable values ​​stored in the stack are all allocated and saved in the stack, and addresses are allocated from top to bottom. The operation mode is similar to the stack in the data structure, such as int a=10, automatic allocation and automatic recovery. The program accesses local variables through the base address and offset of the stack.

2) Heap : The application program requests the operating system to allocate its own memory when it is running, which is requested and released by the programmer, so it is dynamically requested. There is no difference between access to the heap and access to general memory.

The starting address of the heap area is generally low, and the address increases upward. If the programmer does not release it, the OS may reclaim it when the program ends. The allocation method is similar to a linked list. For example, we define int[] arr=new int[10].

Java and C/C++ are different about the heap

  1. In Java, except for simple types (int, char, etc.), memory is allocated in the heap, which is also a main reason for slow programs
  2. C/C++ is not automatically initialized. C/C++ uses malloc/New to request Heap allocation and free/delete to destroy memory.
  3. Heap memory allocation in Java is automatically initialized. All objects in Java (including int wrapper Integer) are allocated in the heap.
  4. In other words, for example, when a String creates an object, memory is allocated from two places. The memory allocated in Heap actually creates this object, while the memory allocated in Stack is just a pointer (reference) to this heap object.

Cache method

  1. The stack uses the first level cache, and the data life cycle on the stack is only in the function running process, it is released immediately after the call, and can no longer be accessed thereafter.
  2. The heap is stored in the second-level cache, and the life cycle is determined by the garbage collection algorithm of the virtual machine (not that it can be recycled once it becomes an orphan). Therefore, the speed of calling these objects is relatively low.

Application response

Stack: As long as the remaining space of the stack is greater than the requested space, the system will provide memory for the program, otherwise an exception will be reported to indicate stack overflow.
Heap: First of all, you should know that the operating system has a linked list that records free memory addresses. When the system receives an application from the program, it will traverse the linked list to find the first heap with a larger space than the requested space.
In C++, the heap is not allocated in the process space beforehand and needs to be allocated manually. At this time, access to the heap space will report a memory access error, and Java will automatically initialize it.

Heap memory allocation process
1) The record linked list deletes the appropriate heap node from the free node linked list, and allocates the space of the node to the program.
2) For most systems, the size of this allocation will be recorded at the first address in this memory space, so that the delete statement in the code can correctly release the memory space.
3) Since the size of the found heap node may not be exactly equal to the size of the application, the system will automatically put the extra part into the free list.
堆会在申请后还要做一些后续的工作,这就会引出申请效率的问题。

Stack memory allocation process
When the process is initialized in C++, the system will automatically create a default stack for the process. The default memory size of this stack varies according to different systems.
Each thread of the process has a private "stack", so although the code of each thread is the same, the data of local variables does not interfere with each other. A stack can be described by the "base address" and the "top of stack" address.

Stack access

1) There is a set of CPU instructions that can implement stack access to the memory of the process. Among them, the POP instruction implements the stack operation, and the PUSH instruction implements the stack operation.
2) The ESP register of the CPU stores the stack top pointer of the current thread, and the EBP register stores the stack bottom pointer of the current thread.
3) The EIP register of the CPU stores the memory address of the next CPU instruction. When the CPU finishes executing the current instruction, it reads the memory address of the next instruction from the EIP register, and then continues execution.

Application efficiency

Stack: automatically allocated by the system, faster. But the programmer cannot control it.

Heap: It is the memory allocated by new, which is generally slower and prone to memory fragmentation, but it is the most convenient to use.
Due to the memory allocation managed by the operating system, it takes time to allocate and destroy, so the efficiency of using the heap is much lower! But the advantage of the heap is that it can be done a lot, C/C++ does not initialize the allocated Heap.

Application size limit

Stack: Under Windows, the stack is a data structure extended to lower addresses, and is a contiguous memory area. The address at the top of the stack and the maximum capacity of the stack are pre-defined by the system, and the stack under windows is generally only 1-2M. If the requested space exceeds the remaining space of the stack, a stack overflow will be prompted.

Heap: Heap is a data structure that extends to high addresses and is a discontinuous memory area. This is because the system uses a linked list to store free memory addresses, which are naturally discontinuous, and the traversal direction of the linked list is from low addresses to high addresses. The size of the heap is limited by the effective virtual memory in the computer system. It can be seen that the space obtained by the heap is more flexible and larger.

** 由于栈的大小有限,所以用子函数还是有物理意义的,而不仅仅是逻辑意义。**Using more rows of sub-functions and control functions can effectively reduce the pressure on the stack size limit.

Store content

Stack: When a function is called, the first to be pushed onto the stack is the address of the next instruction (the next executable statement of the function call statement) after the function call in the main function, and then the parameters of the function.
In most C compilers, the parameters are pushed onto the stack from right to left, and then the local variables in the function.注意静态变量是不入栈的。

When the function call is over, the local variables are popped out of the stack first, then the parameters, and finally the pointer on the top of the stack points to the initial address, which is the next instruction in the main function, and the program continues from this point.

Heap: Generally, one byte is used to store the size of the heap at the head of the heap. The specific content in the heap is arranged by the programmer.

to sum up

Some people liken the stack to go to a restaurant to eat, eat only after ordering, which is quick and has little freedom. Dumpling is like cooking by yourself, the process is troublesome, but you have a high degree of freedom when you want to eat and cook.

博客书写不易,您的点赞收藏是我前进的动力,千万别忘记点赞、 收**藏 ^ _ ^ !

Related Links

Guess you like

Origin blog.csdn.net/luo_boke/article/details/107110322