Virtual memory: address translation with a page table
Virtual memory gives each process its own address space. The program uses virtual addresses and hardware, with the operating system's help, translates them to physical addresses. Memory is divided into fixed-size pages in the virtual space and equal-size frames in physical memory.
Python
PAGE_SIZE = 4096
page_table = {0: 5, 1: 2, 2: None, 3: 7}
def translate(address):
page, offset = divmod(address, PAGE_SIZE)
if page not in page_table:
return "segmentation fault"
frame = page_table[page]
if frame is None:
return "page fault"
return frame * PAGE_SIZE + offset
print(PAGE_SIZE.bit_length() - 1)
for address in (0, 4100, 8200, 16383, 20000):
print(address, translate(address))