Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Virtual Memory and Page Replacement

1 topic · 28 Nov 2026
1

Virtual Memory and Page Replacement ★★★★★

Operating System

Virtual memory lets a program use more memory than physically available by keeping only the needed pages in RAM (demand paging). Accessing a page that is not in RAM causes a page fault. Too many page faults = thrashing.

Example: reference string 7 0 1 2 0 3 0 4, 3 frames

AlgorithmIdeaPage faults
FIFOReplace the page that came in first7
LRUReplace the least recently used page6
OptimalReplace the page not needed for the longest time (theoretical best)6

Belady's anomaly: with FIFO, adding more frames can sometimes increase page faults.

LRU page faults · C++
int lruFaults(vector<int> refs, int frames) {
    list<int> cache;                       // front = most recently used
    int faults = 0;
    for (int p : refs) {
        auto it = find(cache.begin(), cache.end(), p);
        if (it != cache.end()) cache.erase(it);          // hit
        else {
            faults++;
            if (cache.size() == frames) cache.pop_back(); // evict LRU
        }
        cache.push_front(p);
    }
    return faults;
}