Virtual Memory Management, virtual memory

Source: Internet
Author: User

Virtual Memory Management [Switch], virtual memory

Modern Operating systems generally use Virtual Memory Management (vmmemory Management) mechanisms, which requires support from MMU (Memory Management Unit) in the processor. The concepts of PA and VA are introduced first.

1. PA (Physical Address) --- Physical Address

If the processor does not have an MMU, or the MMU is not enabled, the memory address sent by the CPU execution unit is directly transferred to the Chip Pin, which is called the physical memory, to distinguish it from the virtual memory), which is called the PA (Physical Address, PA), as shown in.

Physical address

2. VA (Virtual Address) --- Virtual Address

If MMU is enabled for the processor, the memory Address sent by the CPU Execution Unit will be intercepted by MMU. The Address from CPU to MMU is called Virtual Address (VA ), MMU translates this address into another address and sends it to the external address pin of the CPU chip, that is, ing VA to PA, as shown in.

Virtual Address

If it is a 32-bit processor, the inner address bus is 32-bit, connected to the CPU Execution Unit (only four address lines are shown in the figure ), the external address bus after MMU conversion is not necessarily 32-bit. That is to say,The virtual address space and physical address space are independent.The virtual address space of the 32-bit processor is 4 GB, and the physical address space can be larger than or less than 4 GB.

MMU maps VA to PA isIn PageThe page size of the 32-bit processor is usually 4 kb. For example, MMU can map a page 0xb7001000 ~ 0xb7001fff ing to one page of PA 0x2000 ~ 0x2fff: If the CPU Execution Unit needs to access the virtual address 0xb7001008, the physical address actually accessed is 0x2008. Pages in the physical memory are called physical pages or Page frames ). Which Page of the virtual memory is mapped to the physical memory? Which Page frame is described through the Page Table. The Page Table is saved in the physical memory, MMU searches the page table to determine the PA to which a VA is mapped.

 

3. process address space

 

The virtual address space of the x86 platform is 0x0000 0000 ~ 0 xffff ffff, roughly the first 3 GB (0x0000 0000 ~ 0 xbfff ffff) is the user space, the last 1 GB (0xc000 0000 ~ 0 xffff ffff) is the kernel space.

Text Segmest and Data Segment
  • Text Segment, Including. text,. rodata, And. plt segments. Is loaded from/bin/bash to the memory, and the access permission is r-x.
  • Data Segment, Including. data and. bss segments. It is also loaded from/bin/bash to the memory, and the access permission is rw -.
Stack and stack
  • Heap): The heap is nothing more than the remaining space in the computer memory. The malloc function allocates the memory dynamically here. Heap space can increase to a high address when the memory is dynamically allocated. The address ceiling of the heap space is called Break. To increase the heap space to a high address, it is necessary to raise the Break and map the new virtual memory page to the physical memory, which is implemented by calling brk by the system, the malloc function also calls brk to allocate memory to the kernel request.
  • Stack)Stack is a specific memory area. The high-address part stores the environment variables and command line parameters of the process, and the low-address part stores the function stack frame, stack space is growing to a low address, but obviously there is no room for growth as the heap space is so large, because it is not uncommon for actual applications to dynamically allocate a large amount of memory, however, there are dozens of layers of function calls, and each layer of calls has many local variables, which are rare.

If you do not pay attention to the memory allocation during program writing, the following problems may occur in the heap and stack areas:

4. Role of Virtual Memory Management

The process address space is independent.

Discontinuous PA can be mapped to consecutive VA.

As shown in. The first figure shows how to save the data on the physical page to the disk, unmap the address, and release the physical page. The second figure is an inbound switch. allocate one from the idle physical page, load the temporary disk page back to the memory, and create address ing.

Form feed

5. malloc and free

The C standard library function malloc can dynamically allocate memory in the heap space, and its underlying layer applies for memory from the operating system through the brk system call. After the dynamically allocated memory is used up, it can be released with free. More accurately, it is returned to malloc, so that the memory can be allocated again when malloc is called next time.

1 # include <stdlib. h> 2 void * malloc (size_t size); // return value: the first address of the allocated memory space is returned successfully. If an error occurs, NULL3 void free (void * ptr) is returned );
 

The size parameter of malloc indicates the number of bytes to be allocated. If the allocation fails (possibly because the system memory is exhausted), NULL is returned. Since the malloc function does not know what type of data the user needs to store in the memory, the general pointer void * is returned, and the user program can convert it to another type of pointer to access the memory. The malloc function ensures that the pointer it returns points to the address that meets the system's alignment requirements. For example, the pointer returned on a 32-bit platform must be aligned to the 4-byte boundary, to ensure that the user program converts it to any type of pointer can be used.

After the dynamically allocated memory is used up, it can be released with free. The parameter passed to free is the first address of the memory block returned by the previous malloc.

Example

Example:

 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 typedef struct { 5     int number; 6     char *msg; 7 } unit_t; 8 int main(void) 9 {10     unit_t *p = malloc(sizeof(unit_t));11     if (p == NULL) {12         printf("out of memory\n");13         exit(1);14     }15     p->number = 3;16     p->msg = malloc(20);17     strcpy(p->msg, "Hello world!");18     printf("number: %d\nmsg: %s\n", p->number, p->msg);19     free(p->msg);20     free(p);21     p = NULL;22     return 0;23 }

 

Description
  • unit_t *p = malloc(sizeof(unit_t));In this sentence, the right side of the equal sign isvoid *Type. The value is displayed on the left of the equal sign.unit_t *Type. The compiler will perform implicit type conversion.void *Type and any pointer type can be implicitly converted to each other.
  • Although memory depletion is a very common error, writing programs should be standardized. After malloc, you should determine whether the program is successful. Most of the system functions to be learned in the future have successful return values and failed return values. Each time you call a system function, you should determine whether the system function is successful or not.
  • free(p);After that, the memory space indicated by p is returned, but the value of p is not changed, because from the perspective of the free function interface, the value of p cannot be changed, the memory space that p points to does not belong to the user. In other words, p becomesWild pointerTo avoid the occurrence of a wild pointer, we shouldfree(p);Then manually setp = NULL;.
  • Should firstfree(p->msg), Againfree(p). Iffree(p), P becomes a wild pointer, so it cannot passp->msgThe memory is accessed.
6. Memory leakage

If a program runs for years (for example, a network server program) and calls malloc to allocate memory in a loop or recursion, there must be a free pair,Release once for allocationOtherwise, the system Memory will be slowly exhausted after each cycle is allocated and not released. This error is called Memory leakage (Memory Leak ). In addition,The pointer returned by malloc must be saved.Only pass it to free can this memory be released. If this pointer is lost, there will be no way to free this memory and it will cause memory leakage. For example:

1 void foo(void)2 {3     char *p = malloc(10);4     ...5 }

When the foo function returns, it will release the memory space of the local variable p. The memory address it points to will be lost, and the 10 bytes will not be released. The Bug of Memory leakage is hard to find, because it does not cause program running errors as if the access was out of bounds. A small amount of memory leakage does not affect the proper running of the program. A large amount of memory leakage will cause system memory shortage, frequent page changes not only affect the current process, but also slow the entire system.

There are some special cases about malloc and free. The call of malloc (0) is also legal, and a non-NULL pointer is returned. This pointer can also be passed to free for release, but cannot be used to access the memory. Free (NULL) is also legal and does nothing, but free a wild pointer is illegal. For example, calling malloc first returns a pointer p, call free (p) twice in a row, and the next call will produce a runtime error.

 

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.