Joke Collection Website - Talk about mood - What does the operating system do when dynamically requesting memory?

What does the operating system do when dynamically requesting memory?

More specifically:

1. For the definition of variables, local variables are indeed placed in the stack, but static variables or global variables are placed in the program data section; The memory requested by dynamic memory is allocated from the heap. Stack and data segments are managed and used by programs, while the allocation and recovery of memory in the heap must be managed by the system.

2. When the program dynamically applies for memory, the program applies to the front-end allocator of the heap manager in the system through the API. If there is suitable memory in the heap segment, allocate it to the program. If not, the heap manager is applied to the system virtual memory manager through the back-end allocator.

3. The memory occupied by the initial heap segment, stack, code segment and data segment is allocated by the system virtual memory manager when the process is created.

4. When creating a process, many complicated operations will be carried out, such as applying for memory from the system memory pool to create the key structure of the process, such as page tables and kernel objects, creating the virtual memory space of the process, allocating memory loader from the virtual memory space, and allocating memory initialization heap and stack from the virtual memory space.

5. The virtual memory manager only manages the virtual memory, and the virtual memory address needs to be converted into the physical memory address of the virtual memory twice through segmentation and paging. When you access virtual memory, it may not correspond to physical memory, or it may be switched to hard disk, so it is also the task of the system to ensure that you can access the correct physical memory.

6. To allocate memory, the virtual memory manager must first find a suitable address in the virtual address space, then find a suitable physical memory from the page frame database, map this physical memory to this virtual address through segmentation and paging mechanism, and then return this address to the applicant.

7. Except for the application of dynamic memory, all other memories are used in process initialization, so it is not necessary to apply them again when using them, and the efficiency is of course high. When applying for dynamic memory, the process may be simple. The program calls the API to apply to the heap manager, and the heap manager finds a piece of memory for you from the initialized heap segment. Sometimes this process can be complicated. The program asks the heap manager, which asks the virtual memory manager, and the virtual memory manager asks the physical memory manager.

8. In a word, this is a very complicated process, which also shows the powerful function of an operating system in resource management.