Lab Report: Page Replacement Algorithms
Date of Completion: 11 September 2025
Objectives: Implement FIFO and LRU page replacement algorithms and compute page faults for a given
reference string.
Theory (expanded): When a page not present in memory is referenced, a page fault occurs.
Replacement policy decides which resident page to evict. FIFO is simple but may remove frequently used
pages; LRU approximates Belady's optimal algorithm by removing the least recently used page. LRU can
be implemented with counters, timestamps, or a stack/list with updates on each reference; hardware
support often uses reference bits and aging approximations.
Flowchart (LRU):
[Start] -> For each page in reference string -> If page in frame: update recency -> Else: if free frame: load
page -> else: evict least recently used -> load page -> page_fault++ -> Repeat -> End
Program (page_replacement.c)
/* page_replacement.c
Implements FIFO and LRU (using timestamps)
Compile: gcc -o page_replacement page_replacement.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int fifo(int pages[], int n, int frames) {
int *f = calloc(frames, sizeof(int)); for (int i=0;i<frames;i++) f[i]=-1;
int pointer=0, faults=0;
for (int i=0;i<n;i++) {
int found=0;
for (int j=0;j<frames;j++) if (f[j]==pages[i]) { found=1; break; }
if (!found) {
f[pointer] = pages[i];
pointer = (pointer+1)%frames;
faults++;
}
}
free(f);
return faults;
}
int lru(int pages[], int n, int frames) {
int *f = calloc(frames, sizeof(int)); for (int i=0;i<frames;i++) f[i]=-1;
int *time = calloc(frames, sizeof(int)); for (int i=0;i<frames;i++) time[i]=0;
int faults=0, clk=0;
for (int i=0;i<n;i++) {
clk++;
int found=-1;
for (int j=0;j<frames;j++) if (f[j]==pages[i]) { found=j; break; }
if (found!=-1) { time[found]=clk; continue; }
// miss
int empty = -1;
for (int j=0;j<frames;j++) if (f[j]==-1) { empty=j; break; }
if (empty!=-1) { f[empty]=pages[i]; time[empty]=clk; faults++; continue; }
// find LRU
int lru_index=0, min=time[0];
for (int j=1;j<frames;j++) if (time[j] < min) { min=time[j]; lru_index=j; }
f[lru_index] = pages[i]; time[lru_index]=clk; faults++;
}
free(f); free(time);
return faults;
}
int main() {
int pages[] = {7,0,1,2,0,3,0,4,2,3,0,3,2};
int n = sizeof(pages)/sizeof(pages[0]);
int frames = 3;
printf("FIFO faults = %d\n", fifo(pages,n,frames));
printf("LRU faults = %d\n", lru(pages,n,frames));
return 0;
}
Sample Output:
FIFO faults = 9
LRU faults = 9 (example; depends on string and frames)