Reading history

LRU Cache in C: Hash Table plus Doubly Linked List

8 min read 0 views

Build an O(1) LRU cache in C by combining a hash table with a doubly linked list, and compare LRU with FIFO page replacement.

A cache keeps a small amount of recently used data close at hand, so it can be fetched quickly. When the cache is full and something new arrives, one item must go. A popular rule is LRU (least recently used): throw out the item that has gone unused for the longest time. Web browsers, databases and operating systems all use this idea. This lesson builds an LRU cache in C where both get and put run in O(1), by combining two data structures you already know.

In this lesson you will learn

  • What an LRU cache does
  • Why one data structure alone is not enough
  • How a hash table and a doubly linked list work together
  • How sentinel nodes simplify the list code
  • How LRU compares with FIFO for page replacement

You should know doubly linked lists, hashing and dynamic memory allocation.

The Design

We need three operations to be fast: find a key, mark it as most recently used, and remove the least recently used item.

  • A hash table finds a key in O(1) on average, but it has no idea of order.
  • A doubly linked list keeps items in order of use and can move or remove a node in O(1), but finding a key in it takes O(n).
  • Together they cover each other’s weakness. The hash table maps each key to its node in the list.
hash tablekey 1key 3key 4doubly linked list (most recent → least recent)head4:4001:1003:300tailevict from herenew / used items go here

The Implementation

#include <stdio.h>
#include <stdlib.h>

/* LRU cache: hash table for O(1) lookup + doubly linked list for O(1) reordering.
   Most recently used is at the head; least recently used is at the tail. */
typedef struct Node { int key, value; struct Node *prev, *next, *hnext; } Node;

#define BUCKETS 16
typedef struct {
    int capacity, size;
    Node head, tail;            /* sentinel nodes: no NULL checks needed */
    Node *table[BUCKETS];
} LRU;

static void unlink_node(Node *n) { n->prev->next = n->next; n->next->prev = n->prev; }
static void push_front(LRU *c, Node *n) {
    n->next = c->head.next; n->prev = &c->head;
    c->head.next->prev = n; c->head.next = n;
}
static Node *find(LRU *c, int key) {
    for (Node *n = c->table[key % BUCKETS]; n; n = n->hnext) if (n->key == key) return n;
    return NULL;
}
static void table_remove(LRU *c, Node *t) {
    Node **p = &c->table[t->key % BUCKETS];
    while (*p != t) p = &(*p)->hnext;
    *p = t->hnext;
}

static void init(LRU *c, int cap) {
    c->capacity = cap; c->size = 0;
    c->head.next = &c->tail; c->tail.prev = &c->head;
    for (int i = 0; i < BUCKETS; i++) c->table[i] = NULL;
}

static int get(LRU *c, int key) {
    Node *n = find(c, key);
    if (!n) return -1;
    unlink_node(n); push_front(c, n);       /* now the most recently used */
    return n->value;
}

static void put(LRU *c, int key, int value) {
    Node *n = find(c, key);
    if (n) { n->value = value; unlink_node(n); push_front(c, n); return; }
    if (c->size == c->capacity) {           /* evict the least recently used */
        Node *old = c->tail.prev;
        printf("  (evict key %d)\n", old->key);
        unlink_node(old); table_remove(c, old); free(old); c->size--;
    }
    n = malloc(sizeof *n);
    n->key = key; n->value = value;
    n->hnext = c->table[key % BUCKETS]; c->table[key % BUCKETS] = n;
    push_front(c, n); c->size++;
}

static void show(LRU *c) {
    printf("  cache (recent -> old):");
    for (Node *n = c->head.next; n != &c->tail; n = n->next) printf(" [%d:%d]", n->key, n->value);
    printf("\n");
}

int main(void) {
    LRU c; init(&c, 3);
    printf("put 1, 2, 3\n"); put(&c, 1, 100); put(&c, 2, 200); put(&c, 3, 300); show(&c);
    printf("get 1 -> %d\n", get(&c, 1)); show(&c);
    printf("put 4\n"); put(&c, 4, 400); show(&c);
    printf("get 2 -> %d\n", get(&c, 2));
    printf("put 3 = 333\n"); put(&c, 3, 333); show(&c);
    printf("put 5\n"); put(&c, 5, 500); show(&c);

    while (c.head.next != &c.tail) { Node *n = c.head.next; unlink_node(n); free(n); }
    return 0;
}

Output

put 1, 2, 3
  cache (recent -> old): [3:300] [2:200] [1:100]
get 1 -> 100
  cache (recent -> old): [1:100] [3:300] [2:200]
put 4
  (evict key 2)
  cache (recent -> old): [4:400] [1:100] [3:300]
get 2 -> -1
put 3 = 333
  cache (recent -> old): [3:333] [4:400] [1:100]
put 5
  (evict key 1)
  cache (recent -> old): [5:500] [3:333] [4:400]
  • Sentinels: head and tail are dummy nodes that are always there. Every real node has a node before and after it, so unlink_node and push_front never need to check for NULL.
  • get: look up the key in the hash table. If found, move its node to the front, because it has just been used.
  • put: if the key exists, update its value and move it to the front. Otherwise, if the cache is full, remove the node just before tail, which is the least recently used. Then add the new node at the front.
  • In the run, get 1 moves key 1 to the front, so when 4 arrives, key 2 is evicted instead. Later put 3 = 333 updates key 3 in place and makes it the newest.
  • Each hash bucket is a short chain of nodes linked by hnext, so collisions are handled by chaining.
  • The program frees every node at the end. Running it under a memory checker such as Valgrind shows no leaks.

LRU in Operating Systems

Operating systems face the same problem with memory pages. When memory is full and a new page is needed, one page must be swapped out. Each time a needed page is not in memory, a page fault occurs.

#include <stdio.h>

/* Count page faults for a reference string with FIFO and LRU replacement
   (the same idea operating systems use for memory pages). */
static int simulate(const int *refs, int n, int frames, int lru) {
    int page[8], stamp[8], used = 0, faults = 0;
    for (int t = 0; t < n; t++) {
        int hit = -1;
        for (int i = 0; i < used; i++) if (page[i] == refs[t]) hit = i;
        if (hit >= 0) { if (lru) stamp[hit] = t; continue; }   /* LRU refreshes on use */
        faults++;
        if (used < frames) { page[used] = refs[t]; stamp[used++] = t; continue; }
        int victim = 0;                                        /* smallest stamp = oldest */
        for (int i = 1; i < used; i++) if (stamp[i] < stamp[victim]) victim = i;
        page[victim] = refs[t]; stamp[victim] = t;
    }
    return faults;
}

int main(void) {
    int refs[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
    int n = 13;
    printf("References:");
    for (int i = 0; i < n; i++) printf(" %d", refs[i]);
    printf("\n");
    for (int f = 3; f <= 4; f++)
        printf("%d frames: FIFO faults = %d, LRU faults = %d\n",
               f, simulate(refs, n, f, 0), simulate(refs, n, f, 1));
    return 0;
}

Output

References: 7 0 1 2 0 3 0 4 2 3 0 3 2
3 frames: FIFO faults = 10, LRU faults = 9
4 frames: FIFO faults = 7, LRU faults = 6
  • FIFO removes the page that arrived first, even if it is used all the time. LRU removes the page unused for the longest time.
  • For this reference string, LRU causes fewer faults with both 3 and 4 frames, because recently used pages tend to be used again soon. This pattern is called locality of reference.
  • The simulation keeps a time stamp for each page. LRU updates the stamp on every use; FIFO only sets it when the page is loaded.

Common Replacement Policies

PolicyRemovesNotes
FIFOThe oldest item to arriveSimple, but ignores how often items are used
LRUThe item unused for the longest timeWorks well in practice; O(1) with hash table + list
LFUThe least frequently used itemKeeps popular items, but old favourites can linger
Optimal (Belady)The item that will be needed furthest in the futureBest possible, but needs to know the future; used for comparison only

Common Mistakes

  1. Using a singly linked list, so removing a node needs an O(n) search for its predecessor.
  2. Forgetting to move a node on get, which turns LRU into FIFO.
  3. Removing a node from the list but not from the hash table, leaving a dangling pointer.
  4. Not freeing evicted nodes, which leaks memory.

Practice Exercises

Exercise 1. A cache of size 2 receives: put 1, put 2, get 1, put 3, get 2. What does the final get return?

Show answer

−1. After get 1, key 2 is the least recently used, so put 3 evicts it.

Exercise 2. What is the time complexity of get and put, and why?

Show answer

O(1) on average. The hash table finds the node in O(1) on average, and the doubly linked list moves or removes it in O(1) using its prev and next pointers.

Frequently Asked Questions

Do real systems use exact LRU?

Often not. Updating a list on every memory access is too costly for hardware, so systems use cheap approximations such as the “clock” algorithm, which uses one “recently used” bit per page.

Can FIFO get worse with more memory?

Strangely, yes. With FIFO, adding more frames can sometimes cause more page faults. This is called Belady’s anomaly. LRU never has this problem.

Summary

  • An LRU cache evicts the item that has gone unused the longest.
  • A hash table finds nodes; a doubly linked list keeps them in order of use.
  • get and put both run in O(1) on average.
  • LRU usually beats FIFO because recently used data tends to be used again.

Next: Maximum Flow in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *