Memory and paging
Every process gets its own memory. Here is how it is laid out and how the OS fits it into RAM.
Memory layout
A process's memory has a few parts:
- Code: the program's instructions.
- Stack: space for function calls and their local values.
It grows when a function is called and shrinks when the function returns.
- Heap: memory the program asks for while it runs, when the size is not known in advance.
Virtual addresses
A process never sees real RAM addresses. It uses virtual addresses, and the hardware and OS turn each one into a real address in RAM. So two processes can both use address 1000 and reach different places in RAM.
Pages and frames
Virtual memory is cut into fixed-size blocks called pages. RAM is cut into blocks of the same size called frames. A common size is 4 KB, which is 4096 bytes. Any page can go in any free frame, so a process never needs one long free stretch of RAM.
Page table
Each process has its own page table. It maps each page number to the frame that holds it. To turn a virtual address into a real one, the hardware looks up the page in the table, finds the frame, and keeps the same offset inside it. When the OS switches processes, it switches page tables too.
Page fault
Some pages are not in RAM right now; they may be on disk. Touching one of them causes a page fault. This is normal: the OS loads the page into a frame, updates the page table, and the program carries on. Only an address the process was never given is a real error, and then the OS stops the process.
Remember
- Stack for function calls, heap for memory asked for while running.
- Each process has its own virtual addresses.
- Pages (virtual) and frames (RAM) are the same size.
- The page table maps pages to frames, one table per process.
- A page fault is usually normal, not a crash.