Show contents
Chapter 2 of 7 · 20 min
A hash table
By the end of this chapter, you'll be able to
- Explain the principle of a hash function and a bucket
- Handle collisions by chaining, with one list per bucket
- Copy the keys so that the table owns its own data
- Free a table entirely, keys included
The principle
- A hash function turns a key (here a string) into a large number. The same key always gives the same number.
- The remainder of dividing by the number of buckets gives the bucket index:
hash(key) % NB_BUCKETS. - Two different keys can land in the same bucket: that's a collision. It's handled by chaining: each bucket holds a small linked list of the entries that land there.
We create an entry at the front of that list. On the next green vote, we'll find it and add 1.
Step 5 of 5
Text description of the animation
- We want to add a vote for "green".
- The hash function combines all the key's bytes into a single number.
- The remainder of dividing by 8 gives the bucket: we only look at that one, not the whole table.
- We go through bucket 6's small list: "green" isn't there yet.
- We create an entry at the front of that list. On the next green vote, we'll find it and add 1.
A counting table
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NB_BUCKETS 8
typedef struct Entry {
char *key;
int value;
struct Entry *next;
} Entry;
typedef struct {
Entry *buckets[NB_BUCKETS];
} Table;
static unsigned long hash(const char *s) {
unsigned long h = 5381;
for (; *s != '\0'; s++) {
h = h * 33 + (unsigned char)*s;
}
return h;
}
void table_init(Table *t) {
for (int i = 0; i < NB_BUCKETS; i++) {
t->buckets[i] = NULL;
}
}
/* Adds delta to key's value (creates the entry if needed). Returns 0 or -1. */
int table_add(Table *t, const char *key, int delta) {
unsigned long i = hash(key) % NB_BUCKETS;
for (Entry *e = t->buckets[i]; e != NULL; e = e->next) {
if (strcmp(e->key, key) == 0) {
e->value += delta;
return 0;
}
}
Entry *e = malloc(sizeof *e);
if (e == NULL) return -1;
e->key = malloc(strlen(key) + 1);
if (e->key == NULL) {
free(e);
return -1;
}
strcpy(e->key, key);
e->value = delta;
e->next = t->buckets[i];
t->buckets[i] = e;
return 0;
}
int table_value(const Table *t, const char *key) {
for (const Entry *e = t->buckets[hash(key) % NB_BUCKETS]; e != NULL; e = e->next) {
if (strcmp(e->key, key) == 0) return e->value;
}
return 0;
}
void table_free(Table *t) {
for (int i = 0; i < NB_BUCKETS; i++) {
Entry *e = t->buckets[i];
while (e != NULL) {
Entry *next = e->next;
free(e->key);
free(e);
e = next;
}
t->buckets[i] = NULL;
}
}
int main(void) {
Table votes;
table_init(&votes);
const char *ballots[] = {"green", "blue", "green", "orange", "green", "blue"};
for (size_t i = 0; i < sizeof ballots / sizeof ballots[0]; i++) {
if (table_add(&votes, ballots[i], 1) != 0) return 1;
}
printf("green: %d, blue: %d, orange: %d, red: %d\n",
table_value(&votes, "green"), table_value(&votes, "blue"),
table_value(&votes, "orange"), table_value(&votes, "red"));
table_free(&votes);
return 0;
}
green: 3, blue: 2, orange: 1, red: 0
hashis the djb2 function, simple and classic: it multiplies the result by 33 and adds each byte. Overflowing anunsigned longis defined in C (the calculation "wraps round"), unlike overflowing anint.(unsigned char)*sstops an accented byte (above 127) from counting as negative.- The table copies each key (
malloc+strcpy): it owns its data and doesn't depend on how long the caller's strings live. - The cost stays O(1) on average as long as the lists stay short. A real table grows when the number of entries exceeds the number of buckets: the buckets are doubled and each entry is put back in place.
Your turn
Worked exercise
Worked exercise: removing a key
Add to the table a function int table_remove(Table *t, const char *key) that deletes this key's entry, frees its memory (key included) and returns 0, or -1 if the key is missing. Test it: after removing "blue", its value must be 0, the others mustn't move, and removing "blue" a second time must return -1.
Hint 1
It's the linked-list removal from the previous chapter, applied to the right bucket's list: use a pointer to a pointer on
t->buckets[i].Hint 2
Free
e->key before e: once e is freed, you can no longer read its key field.Show the solution and common mistakes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NB_BUCKETS 8
typedef struct Entry {
char *key;
int value;
struct Entry *next;
} Entry;
typedef struct {
Entry *buckets[NB_BUCKETS];
} Table;
static unsigned long hash(const char *s) {
unsigned long h = 5381;
for (; *s != '\0'; s++) h = h * 33 + (unsigned char)*s;
return h;
}
int table_add(Table *t, const char *key, int delta) {
unsigned long i = hash(key) % NB_BUCKETS;
for (Entry *e = t->buckets[i]; e != NULL; e = e->next) {
if (strcmp(e->key, key) == 0) { e->value += delta; return 0; }
}
Entry *e = malloc(sizeof *e);
if (e == NULL) return -1;
e->key = malloc(strlen(key) + 1);
if (e->key == NULL) { free(e); return -1; }
strcpy(e->key, key);
e->value = delta;
e->next = t->buckets[i];
t->buckets[i] = e;
return 0;
}
int table_value(const Table *t, const char *key) {
for (const Entry *e = t->buckets[hash(key) % NB_BUCKETS]; e != NULL; e = e->next) {
if (strcmp(e->key, key) == 0) return e->value;
}
return 0;
}
int table_remove(Table *t, const char *key) {
for (Entry **p = &t->buckets[hash(key) % NB_BUCKETS]; *p != NULL; p = &(*p)->next) {
if (strcmp((*p)->key, key) == 0) {
Entry *e = *p;
*p = e->next;
free(e->key);
free(e);
return 0;
}
}
return -1;
}
int main(void) {
Table t;
for (int i = 0; i < NB_BUCKETS; i++) t.buckets[i] = NULL;
const char *ballots[] = {"green", "blue", "green", "orange", "blue"};
for (size_t i = 0; i < sizeof ballots / sizeof ballots[0]; i++) {
if (table_add(&t, ballots[i], 1) != 0) return 1;
}
printf("remove blue: %d\n", table_remove(&t, "blue"));
printf("blue %d, green %d, orange %d\n", table_value(&t, "blue"), table_value(&t, "green"), table_value(&t, "orange"));
printf("remove blue again: %d\n", table_remove(&t, "blue"));
table_remove(&t, "green");
table_remove(&t, "orange");
return 0;
}
remove blue: 0
blue 0, green 2, orange 1
remove blue again: -1
The last two removals empty the table: AddressSanitizer, which detects leaks at the end of the program, finds nothing to report.
Common mistakes:
- Only freeing the entry (
free(e)): the copy of the key stays allocated, and each removal creates a leak. - Searching for the key in every bucket: it works, but the cost goes back to O(n), which cancels out the whole point of the table.
Summary
- 1A hash table turns the key into a bucket index: O(1) access on average.
- 2Collisions are handled by chaining: one linked list per bucket.
- 3Unsigned integer overflow is defined in C, which suits hash functions.
- 4The table copies its keys and frees them itself.
- 5A table grows when its lists get longer, to stay fast.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.