Reading history

Hash Table in C: Chaining and Open Addressing

9 min read 1 views

Build hash tables in C: djb2 hashing, separate chaining with insert, find and delete, open addressing with linear probing and rehashing.

A hash table stores key–value pairs and finds any key in roughly constant time, whether it holds ten items or ten million. Python dictionaries, Java’s HashMap and database indexes all rely on the idea. C has no built-in hash table, so building one is a classic exercise that brings together structs, pointers, linked lists and dynamic memory. This lesson builds two kinds: one with chaining, and one with open addressing that grows as it fills.

In this lesson you will learn

  • What a hash function does and why collisions happen
  • Separate chaining with a linked list in each bucket
  • Insert, update, find and delete
  • Open addressing with linear probing
  • Load factor and growing the table by rehashing

You should know linked lists, structures and dynamic memory allocation.

Separate Chaining

A hash function turns a key into a number. Taking that number modulo the table size picks a bucket. When two keys land in the same bucket, a collision, both are kept in a short linked list there.

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

#define BUCKETS 8

typedef struct Entry {
    char *key;
    int value;
    struct Entry *next;           /* entries in the same bucket form a linked list */
} Entry;

typedef struct {
    Entry *bucket[BUCKETS];
    int count;
} Table;

/* djb2: a simple, well-known string hash */
unsigned long hash(const char *s) {
    unsigned long h = 5381;
    for (; *s; s++)
        h = h * 33 + (unsigned char)*s;
    return h;
}

Entry *find(Table *t, const char *key) {
    for (Entry *e = t->bucket[hash(key) % BUCKETS]; e; e = e->next)
        if (strcmp(e->key, key) == 0)
            return e;
    return NULL;
}

int put(Table *t, const char *key, int value) {
    Entry *e = find(t, key);
    if (e) { e->value = value; return 1; }       /* update existing key */

    e = malloc(sizeof *e);
    if (!e) return 0;
    e->key = malloc(strlen(key) + 1);
    if (!e->key) { free(e); return 0; }
    strcpy(e->key, key);
    e->value = value;
    unsigned long b = hash(key) % BUCKETS;
    e->next = t->bucket[b];                      /* insert at the front of the chain */
    t->bucket[b] = e;
    t->count++;
    return 1;
}

int remove_key(Table *t, const char *key) {
    Entry **link = &t->bucket[hash(key) % BUCKETS];
    while (*link) {
        Entry *e = *link;
        if (strcmp(e->key, key) == 0) {
            *link = e->next;                     /* unlink, then free */
            free(e->key);
            free(e);
            t->count--;
            return 1;
        }
        link = &e->next;
    }
    return 0;
}

void free_table(Table *t) {
    for (int b = 0; b < BUCKETS; b++) {
        Entry *e = t->bucket[b];
        while (e) {
            Entry *next = e->next;
            free(e->key);
            free(e);
            e = next;
        }
        t->bucket[b] = NULL;
    }
    t->count = 0;
}

int main(void) {
    Table stock = {0};                           /* all buckets start empty */
    put(&stock, "mango", 40);
    put(&stock, "lychee", 25);
    put(&stock, "jackfruit", 6);
    put(&stock, "banana", 120);
    put(&stock, "guava", 30);
    put(&stock, "mango", 35);                    /* update, not a new entry */

    const char *ask[] = {"mango", "guava", "papaya"};
    for (int i = 0; i < 3; i++) {
        Entry *e = find(&stock, ask[i]);
        if (e) printf("%-7s -> %d in stock\n", ask[i], e->value);
        else   printf("%-7s -> not found\n", ask[i]);
    }

    printf("entries: %d\n", stock.count);
    remove_key(&stock, "banana");
    printf("after removing banana: %d, found? %s\n", stock.count, find(&stock, "banana") ? "yes" : "no");

    puts("bucket layout:");
    for (int b = 0; b < BUCKETS; b++) {
        printf("  [%d]", b);
        for (Entry *e = stock.bucket[b]; e; e = e->next)
            printf(" -> %s", e->key);
        printf("\n");
    }
    free_table(&stock);
    return 0;
}

Output

mango   -> 35 in stock
guava   -> 30 in stock
papaya  -> not found
entries: 5
after removing banana: 4, found? no
bucket layout:
  [0] -> jackfruit
  [1] -> guava
  [2]
  [3]
  [4]
  [5]
  [6]
  [7] -> lychee -> mango
  • hash is the well-known djb2 function: start at 5381, and for each character multiply by 33 and add the character. Similar keys get very different numbers, which spreads them across buckets.
  • find only searches the one bucket the key hashes to, not the whole table. That is where the speed comes from.
  • put first checks whether the key exists. “mango” was added twice, so the second call updated its value to 35 instead of adding a duplicate, and the count stayed at 5.
  • New entries go at the front of the bucket’s list, which takes constant time. The key is copied into its own memory, so the table does not depend on the caller’s string staying alive.
  • remove_key uses a pointer to the link (Entry **link) so that removing the first entry and removing a later one need the same code.
  • The bucket layout shows a real collision: “lychee” and “mango” share bucket 7. Table stock = {0}; starts every bucket as NULL.

Open Addressing That Grows

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

/* Open addressing with linear probing, and growing when 70% full */
typedef struct {
    int *keys;
    int *values;
    char *used;
    size_t cap, count;
} IntMap;

static size_t slot_of(int key, size_t cap) {
    return ((unsigned)key * 2654435761u) % cap;     /* multiplicative hash */
}

int map_init(IntMap *m, size_t cap) {
    m->keys = malloc(cap * sizeof *m->keys);
    m->values = malloc(cap * sizeof *m->values);
    m->used = calloc(cap, 1);                       /* all slots start unused */
    m->cap = cap;
    m->count = 0;
    return m->keys && m->values && m->used;
}

void map_free(IntMap *m) {
    free(m->keys); free(m->values); free(m->used);
}

int map_put(IntMap *m, int key, int value);

static int grow(IntMap *m) {
    IntMap bigger;
    if (!map_init(&bigger, m->cap * 2)) { map_free(&bigger); return 0; }
    for (size_t i = 0; i < m->cap; i++)
        if (m->used[i])
            map_put(&bigger, m->keys[i], m->values[i]);   /* re-insert every key */
    map_free(m);
    *m = bigger;
    return 1;
}

int map_put(IntMap *m, int key, int value) {
    if ((m->count + 1) * 10 > m->cap * 7) {          /* keep load below 0.7 */
        if (!grow(m)) return 0;
        printf("  (grew to %zu slots)\n", m->cap);
    }
    size_t i = slot_of(key, m->cap);
    while (m->used[i] && m->keys[i] != key)
        i = (i + 1) % m->cap;                        /* slot taken: try the next one */
    if (!m->used[i]) { m->used[i] = 1; m->keys[i] = key; m->count++; }
    m->values[i] = value;
    return 1;
}

int *map_get(IntMap *m, int key) {
    size_t i = slot_of(key, m->cap);
    while (m->used[i]) {
        if (m->keys[i] == key) return &m->values[i];
        i = (i + 1) % m->cap;
    }
    return NULL;
}

int main(void) {
    IntMap marks;
    if (!map_init(&marks, 4)) return 1;

    int rolls[] = {1201, 1207, 1215, 1222, 1230, 1238, 1243, 1251};
    for (int i = 0; i < 8; i++)
        if (!map_put(&marks, rolls[i], 60 + i * 5)) return 1;

    printf("%zu students in %zu slots\n", marks.count, marks.cap);
    int ask[] = {1215, 1251, 1300};
    for (int i = 0; i < 3; i++) {
        int *v = map_get(&marks, ask[i]);
        if (v) printf("roll %d: %d marks\n", ask[i], *v);
        else   printf("roll %d: not found\n", ask[i]);
    }
    map_free(&marks);
    return 0;
}

Output

  (grew to 8 slots)
  (grew to 16 slots)
8 students in 16 slots
roll 1215: 70 marks
roll 1251: 95 marks
roll 1300: not found
  • Open addressing stores entries directly in arrays, with no linked lists. If the home slot is taken by another key, linear probing tries the next slot, and the next, until it finds the key or an empty slot.
  • The load factor is count / capacity. As it approaches 1, probe sequences get long and the table slows down. map_put keeps it below 0.7 by checking (count + 1) * 10 > cap * 7, which avoids floating-point maths.
  • When the table is too full, grow builds a table twice as large and re-inserts every key, because each key’s slot depends on the capacity. This is called rehashing. Starting with 4 slots, the table grew to 8 and then 16 while storing 8 students.
  • map_get returns a pointer to the value, or NULL when the key is missing, so a mark of 0 can never be confused with “not found”.
  • Deleting from an open-addressing table is tricky, because emptying a slot can break a probe chain. Real implementations mark deleted slots with a special “tombstone” value instead.

Chaining or Open Addressing?

Separate chainingOpen addressing
CollisionsLinked list per bucketProbe for another slot
MemoryOne allocation per entryA few large arrays
SpeedGoodOften faster, because data is close together
DeletingEasyNeeds tombstones
Can be over 100% full?Yes, lists just get longerNo, it must grow

Common Mistakes

  1. Storing the caller’s string pointer instead of a copy. If the caller’s buffer changes, the key changes too.
  2. Using a weak hash, such as the string’s length or first letter, so most keys collide.
  3. Never growing the table, so lookups slow down as data is added.
  4. Freeing an entry before unlinking it, or forgetting to free the copied key.

Practice Exercises

Exercise 1. Add a function to the chaining table that prints the length of the longest bucket chain.

Show answer
int longest_chain(const Table *t) {
    int best = 0;
    for (int b = 0; b < BUCKETS; b++) {
        int len = 0;
        for (const Entry *e = t->bucket[b]; e; e = e->next) len++;
        if (len > best) best = len;
    }
    return best;
}

Exercise 2. Write int increment(Table *t, const char *key) that adds 1 to a key’s value, creating it with value 1 if it does not exist.

Show answer
int increment(Table *t, const char *key) {
    Entry *e = find(t, key);
    if (e) { e->value++; return 1; }
    return put(t, key, 1);
}

This is exactly what a word-counting program needs.

Frequently Asked Questions

Why is a hash table lookup “constant time” if collisions exist?

With a good hash function and a load factor kept below a limit, the average bucket holds only one or two entries. So the average lookup checks a small, fixed number of entries however big the table is. In the worst case, when every key collides, it becomes as slow as a list.

Why not use a sorted array with binary search instead?

Binary search needs about log n steps and inserting into a sorted array means shifting items. A hash table is faster for insert and lookup, but it does not keep keys in order, so use a sorted structure or a tree when you need ordered output.

Summary

  • A hash function picks a bucket; collisions are normal and must be handled.
  • Chaining keeps a linked list in each bucket and makes deletion easy.
  • Open addressing probes for free slots and must grow before it fills up.
  • Keep the load factor low to keep lookups fast.

Next: Binary Search Tree 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 *