Page faults and resident set size
What you'll learn: How your operating system swaps pieces of memory in and out of physical RAM to keep your programs running.
The Illusion of Infinite Space
When you use malloc to request 1GB of memory, the Operating System (OS) is actually "lazy." It doesn't immediately hand you 1GB of physical RAM chips. Instead, it gives you a map of virtual addresses. It’s like a library that promises you a thousand books but only clears off enough shelf space for the one you are currently reading.
The Page Fault: A "Just in Time" Delivery
Memory is managed in blocks called pages (usually 4KB). A page fault occurs when your program tries to access an address that is in your virtual map but isn't currently sitting in physical RAM.
When this happens:
- The CPU pauses your program.
- The OS finds the data (either from a file or a swap area on your disk).
- The OS places that page into a physical RAM slot.
- Your program resumes as if nothing happened.
Resident Set Size (RSS)
The Resident Set Size is the actual amount of physical RAM your program is occupying at this very moment. If your program asks for 100MB but only ever reads the first few bytes, your RSS will be very small. However, if the OS runs out of RAM, it might "evict" some of your pages to the hard drive, causing your RSS to shrink and your program to slow down due to frequent page faults.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// 1. We allocate 100MB, but the RSS barely moves yet.
size_t size = 100 * 1024 * 1024;
char *buffer = malloc(size);
printf("Allocated 100MB. Check your OS monitor—RSS is likely tiny.\n");
printf("Press Enter to touch the memory...");
getchar();
// 2. Writing to memory triggers page faults.
// The OS now must map physical RAM to these addresses.
for (size_t i = 0; i < size; i += 4096) {
buffer[i] = 'A'; // Accessing each page
}
printf("Memory 'touched.' RSS has now grown to ~100MB.\n");
free(buffer);
return 0;
}
Key takeaway
A page fault is the OS quietly loading data into RAM on demand, while the Resident Set Size (RSS) is the measure of how much physical RAM your program is actually using right now.