Differences between the Linux program storage structure and the process structure heap and stack.
Abstract:This article describes the basic structure of the program storage structure (Code area, data segment, and BBS area) and process (Code area, data segment, BBS area, heap, and stack) in Linux ), and the difference between heap and stack.
Linux program storage structure and process structure 1. in Linux, the program is a common executable file. Figure 1 shows the basic situation of an ELF executable file in Linux.
Figure 1 Basic information of executable files in ELF format
It can be seen that this ELF executable file is not transferred to the memory during storage. It is divided into three parts: the code zone (text), the data zone (data) and the initialization zone (bss. the basic description of each section is as follows:
(1) text segment ). it is also called the body section. the machine commands that can be run by the CPU are generally shared in the code area (that is, other code can be accessed and called). The Code area is generally read-only, the reason for making it read-only is to prevent the program from accidentally modifying its commands. therefore, constant data is allocated space in the code segment during compilation. example 1 illustrates this.
Commands in the code area include the operation code and operation object (or object address reference). If it is a specific value, it is directly included in the Code. for local data, space will be allocated in the stack area during runtime, and then the data address will be referenced. For BBS and data areas, the data address will also be referenced in the code.
(2) initialize the global data zone or static data zone, or data segment for short. this area contains the global variables explicitly initialized in the program, and initialized static variables (including Global static variables and local static variables ). however, the variables and string constants declared by const apply for space in the code segment.
(3) The data zone is not initialized, also known as BBS. the stored global variables and static variables are not initialized. the data in the BBS area is initialized to 0 by the kernel or NULL pointer before the program starts execution ).
Example 1 shows that constant data is allocated space in the code segment during compilation.
#include <stdio.h>int main(){ char *buf =NULL; printf("%s\n",buf); return 0;}
Check the size of each segment after compilation:
Add a character constant and a const data constant to the Code:
#include <stdio.h>const int i=10;int main(){ char *buf = NULL; printf("%s\n",buf); return 0;}
After re-compilation, check that the code segment adds 4 bytes of const I.
2. Linux Process StructureIn Linux, if an executable file in ELF format is loaded into the memory for running, it will evolve into one or more processes. processes are the basic management unit of Linux transactions. All processes have their own independent environments and resources. the process environment is determined and composed of the current system status and its parent process information.
A running process applies for code areas in the memory space, initializes data areas, uninitialized data areas, context information, and mounted signals.
(1) In the code area, the code segment of the executable file is loaded, and its location in the memory is completed by the loader.
(2) initialize the data zone and static data zone globally. the data segment of the executable file is loaded, which can be separated after the code segment. at the beginning of running, the program applied for space for the data segment and was released only when the program exited. Therefore, the data stored in the data segment is stored throughout the program running.
(3) Data zone not initialized. the executable file BBS segment is loaded, which can be separated or closely connected to the data segment. at the beginning of running, the program applied for space for this part and was released only when the program exited. the life cycle of the data stored in this part is the entire program running process.
(4) stack. released automatically by the compiler. the automatic variables and the information to be saved for each function call are stored in this section. each time a function is called, its return address and caller's environment information are stored in the stack. then, the recently called function automatically allocates storage space for it and temporary variables on the stack. stack can be used in this way to call the C function recursively. each time a recursive function calls itself, a new stack frame is used. Therefore, the variable set in one function call instance does not affect the variables in another function call instance.
(5) heap, which is usually dynamically stored and allocated in the heap. generally, it is assigned and released by the programmer. If the programmer does not release the program, the program is terminated by the system. the heap is located between non-initialized data segments and stacks.
Figure 2 shows a comparison between the executable file storage structure in ELF format and the basic structure of Linux processes.
Figure 2 Layout of executable files and process storage
3. Why are there so many zones?(1) The code segment and data segment are separated, which is easy to load separately during operation. The processor of the Harvard architecture will achieve better pipeline processing efficiency.
(2) The code is executed in sequence, read by the PC pointer of the processor, and the code can be shared by multiple programs. The data may be used multiple times during the entire operation, if code and data are mixed together, space is wasted.
(3) The temporary data and the code to be used again are put into the stack at runtime, and the life cycle is short, so as to improve resource utilization.
(4) The heap area can be allocated and released by programmers, so that users can freely allocate and improve program flexibility.
4. Stack and stack differencesStack is the space allocated by the compiler when the program is running and maintained by the operating system. the heap is a memory block allocated by the malloc () function. The memory management is manually controlled by the programmer and completed by using the free () function in the C language. the main differences are as follows:
(1) different management methods
During running, the stack of a program is automatically managed by the operating system without the need of manual control by the programmer. The application and release of the heap space are controlled by the programmer, which may cause memory leakage.
(2) Different space sizes
Stack is an area of continuous memory that expands to a low address. that is, the stack top address and the maximum stack capacity are pre-defined by the system. When the requested space exceeds the remaining stack space, the stack overflow error will occur. the heap is extended to the high address and is a non-sequential memory area. because the system uses a linked list to store idle memory addresses, and the traversal direction of the linked list is from low address to high address.
(3) different fragments are generated.
For the heap, frequent malloc/free will inevitably lead to memory space disconnections, resulting in a large number of fragments, reducing program efficiency. For the stack, it must be a continuous physical memory space.
(4) Different Growth Modes
On the X86 platform, the growth direction of the stack is upward, that is, to the memory address increase direction; stack growth direction is downward, that is, to the memory address decreases direction.
(5) different allocation methods
Heap is a program that dynamically applies for allocation by the malloc () function and is released by the free () function; stack allocation and release are completed by the operating system, and stack dynamic allocation includes alloca () the function is complete, but the stack's dynamic allocation is different from the heap, which is allocated and released by the compiler without manual completion.
(6) Different Allocation Efficiency
The stack is provided by the system, and the operating system will provide support for the stack at the underlying layer: assign a special register to store the stack address, and pressure the stack to exit the stack is dedicated command execution. heap is provided by the C function library. Its mechanism is very complicated. For example, to allocate a piece of memory, the operating system needs to refresh the memory and search for and sort out the memory space, in this way, you have the opportunity to allocate enough memory and then return it. obviously, the heap efficiency is much lower than the stack efficiency.
Author: my personal abilities are limited, just for reference. If the reader finds any errors in this article, please submit them.
--
Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Do not build a high station in the sand float, calm down and slowly accumulate -----------------------------------------Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------------
What is the difference between stack and stack?
I. prerequisites-program memory allocation
The memory occupied by a c/C ++ compiled program is divided into the following parts:
1. stack: the stack is automatically allocated and released by the compiler, storing the parameter values of functions and the values of local variables. The operation method is similar to the stack in the data structure.
2. heap: Generally, it is assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
3. Global (static): stores global variables and static variables. initialized global variables and static variables are stored in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. -The system is released after the program ends.
4. Text Constant Area-constant strings are placed here. The program is released by the System
5. program code area-stores the binary code of the function body.
Ii. Example Program
This is written by a senior. It is very detailed.
// Main. cpp
Int a = 0; global initialization Zone
Char * p1; uninitialized globally
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, and the compiler may optimize it into a place with the "123456" that p3 points.
}
Ii. Theoretical knowledge of heap and stack
2.1 Application Method
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:
The programmer needs to apply and specify the size. In c, the malloc Function
For example, p1 = (char *) malloc (10 );
Use the new operator in C ++
For example, p2 = (char *) malloc (10 );
But note that p1 and p2 are in the stack.
2.2
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 has a linked list that records idle memory addresses. When the system receives a program application,
The linked list is traversed to find the heap node with the first space greater than the requested space. Then, the node is deleted from the idle node linked list and allocated to the program, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that 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 automatically places the excess part in the idle linked list.
2.3 Application size limit
STACK: in Windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In WINDOWS, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. Therefore, the space available from the stack is small.
Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally not consecutive, And the traversal direction of the linked list is from the low address ...... The Rest Of The full text>
Stack and stack in java are different !!!!
First, from the perspective of software design, stack represents the processing logic, while stack represents the data. This separation makes the processing logic clearer. Divide and conquer. This idea of isolation and modularization is embodied in all aspects of software design.
Second, the separation of heap and stack allows the heap content to be shared by multiple stacks (it can also be understood as multiple threads accessing the same object ). There are a lot of benefits for such sharing. On the one hand, this sharing provides an effective way of data interaction (such as shared memory), on the other hand, shared constants and caches in the heap can be accessed by all stacks, saving space.
Third, the stack needs to divide the address segment because of its runtime needs, such as saving the context of the system running. Since the stack can only grow up, it will limit the stack's storage capacity. The heap is different. Objects in the heap can dynamically grow as needed. Therefore, the stack and heap splitting makes dynamic growth possible. In the corresponding stack, you only need to record an address in the heap.
Fourth, object-oriented is the perfect combination of stack and stack. In fact, there is no difference between an object-oriented program and a previously structured program in execution. However, the introduction of object-oriented makes the Way of Thinking About Problems change, and it is closer to thinking about natural ways. When we split the object, you will find that the object's attribute is actually data, stored in the heap; and the object's behavior (method) is the running logic, placed in the stack. When writing objects, we actually write the data structure and the data processing logic. I have to admit that the object-oriented design is really beautiful.