man c/hash-tables

Why C programmers write their own hash tables

lib / C 9 mindraft

checked against: glibc 2.42, musl 1.2.5, FreeBSD 15.0, Apple Libc-1752.120.2

You want to count how often each key appears. C gives you arrays, malloc and qsort. Where is the map?

The C standard library has no map

C23’s searching and sorting clause (N3220 7.24.5) has two functions, bsearch and qsort. The library defines no hash table or other associative container.

POSIX: hcreate, hsearch, hdestroy

POSIX has one, in <search.h>, under the XSI option. It is three functions:

int    hcreate(size_t nel);
void   hdestroy(void);
ENTRY *hsearch(ENTRY item, ACTION action);

nel is “an estimate of the maximum number of entries”, which “may be adjusted upward”. An ENTRY holds a char *key and a void *data, and keys are compared with strcmp(). ACTION is ENTER or FIND. hsearch returns a null pointer when FIND misses or when ENTER finds “the table is full”. After hdestroy, you may call hcreate again. The functions “need not be thread-safe”.

No function takes a table argument, so a process has one table. No action deletes an entry, and nothing iterates or counts. A comment in musl’s source puts it plainly, “with the posix api items cannot be iterated and length cannot be queried”.

The four libraries I read fill in the rest differently:

LibraryLayoutSize from nelGrowsString hash
glibc 2.42open addressing, double hashingfirst prime ≥ nelno, ENTER fails with ENOMEMshift by 4, add char
musl 1.2.5open addressing, quadratic probingpower of two ≥ nel, min 8yes, above 3/431*h + c
FreeBSD 15.0open addressing, quadratic probingignored, starts at 16yes, at 1/2FNV-1a, random seed
macOS (Libc-1752.120.2)separate chainingpower of two ≥ nel, min 16no, chains get longer__default_hash

glibc also has hcreate_r, hsearch_r and hdestroy_r, which take a struct hsearch_data *. They let you have more than one table. glibc’s NEWS lists them, with hsearch itself, under version 2.0. musl added them in 1.1.0, and FreeBSD’s man page calls them GNU extensions. macOS’s libsystem_c.dylib does not export them.

I could only run the macOS version. The rest is from source unless I say otherwise.

glibc’s hash starts with the key length and adds each character after shifting left by 4 bits. It walks the string backwards, so the first character is added last. In a 32-bit unsigned int, characters from the ninth on shift out entirely. I copied the loop from hsearch_r.c and ran it. user_id_0001, user_id_0002, user_id_9999 and user_id_X all hash to 0x5af68ca5. glibc’s probe sequence depends only on that hash, so such keys share one probe path.

macOS uses FreeBSD’s pre-2015 chained version and never resizes. I inserted 100,000 strdup’d keys and looked each one up:

hcreate(nel)ENTER totalFIND per key
162.074 s19,971 ns
131,0720.008 s69 ns

A second hcreate without hdestroy returned 0 with errno set to EINVAL. Apple’s hdestroy also calls free on every key, as its man page says, so keys must come from malloc. glibc’s and musl’s hdestroy free only their own arrays.

So you get one global table of strings with no delete, whose size, growth and key ownership change between libcs. People write their own.

Anatomy of a small open-addressing table

Open addressing keeps every entry in one array. Each slot is empty, full or a tombstone:

index   0     1     2     3     4     5     6     7
state   E     F     F     T     F     E     E     F
key     -    42    17     -    99     -     -     5
                          ^
            deleted entry: lookups step over it, inserts may reuse it

Capacity is a power of two, so an index is a shift or a mask, never a division.

Hash by multiplying and keeping the top bits. Multiply the 64-bit key by 2^64 divided by the golden ratio, rounded down. That is 0x9E3779B97F4A7C15, an odd number, as I checked in Python. Then shift right by 64 minus log2 of the capacity. Linux’s include/linux/hash.h explains why. “Since multiplication propagates changes to the most significant end only, it is essential that the high bits of the product be used for the hash value.” The low k bits of a product depend only on the low k bits of the key. I hashed 1024 keys into 1024 buckets after multiplying:

KeysLow 10 bitsTop 10 bits
i1024897
i * 10241805
i << 321806

Probe linearly. On a collision, try the next slot, wrapping at the end. Neighbours share cache lines. Keys cluster.

Cap the load. Lookups stop at the first empty slot, so there must always be one. This table counts full slots and tombstones together and keeps them at or below 3/4 of capacity.

Delete with tombstones. Emptying a slot would cut the probe path of every key that was pushed past it. A tombstone keeps that path intact. An insert may reuse the first tombstone it passes, but only after probing to an empty slot proves the key is absent. Otherwise the key could end up stored twice.

Grow by rehashing. Rehashing moves only live entries, so tombstones disappear. If the table is mostly tombstones, it rebuilds at the same size instead of doubling.

Here is the whole thing, with a main that counts squares modulo 1000:

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

enum { EMPTY, FULL, TOMB };

typedef struct {
    uint64_t *keys;
    int64_t  *vals;
    uint8_t  *state;
    size_t    cap;    /* always a power of two, at least 8 */
    unsigned  shift;  /* 64 - log2(cap) */
    size_t    live;   /* FULL slots */
    size_t    used;   /* FULL + TOMB slots */
} table;

static size_t slot_of(const table *t, uint64_t key) {
    return (size_t)((key * 0x9E3779B97F4A7C15u) >> t->shift);
}

static void init(table *t, size_t cap) {
    t->keys  = malloc(cap * sizeof *t->keys);
    t->vals  = malloc(cap * sizeof *t->vals);
    t->state = calloc(cap, 1);
    if (!t->keys || !t->vals || !t->state) { perror("malloc"); exit(1); }
    t->cap = cap;
    t->shift = 64;
    for (size_t c = cap; c > 1; c >>= 1) t->shift--;
    t->live = t->used = 0;
}

/* Index of KEY if present; otherwise the slot an insert should use. */
static size_t probe(const table *t, uint64_t key, int *found) {
    size_t mask = t->cap - 1, i = slot_of(t, key), tomb = SIZE_MAX;
    for (;;) {
        if (t->state[i] == EMPTY) {
            *found = 0;
            return tomb != SIZE_MAX ? tomb : i;
        }
        if (t->state[i] == FULL && t->keys[i] == key) {
            *found = 1;
            return i;
        }
        if (t->state[i] == TOMB && tomb == SIZE_MAX) tomb = i;
        i = (i + 1) & mask;
    }
}

static void rehash(table *t, size_t cap) {
    table old = *t;
    init(t, cap);
    for (size_t i = 0; i < old.cap; i++) {
        if (old.state[i] != FULL) continue;
        int found;
        size_t j = probe(t, old.keys[i], &found);
        t->keys[j] = old.keys[i];
        t->vals[j] = old.vals[i];
        t->state[j] = FULL;
        t->live++;
        t->used++;
    }
    free(old.keys); free(old.vals); free(old.state);
}

/* Pointer to KEY's value, inserting it with value 0 if absent. */
static int64_t *upsert(table *t, uint64_t key) {
    int found;
    size_t i = probe(t, key, &found);
    if (found) return &t->vals[i];
    if ((t->used + 1) * 4 > t->cap * 3) {            /* keep load <= 3/4 */
        size_t cap = t->cap;
        if ((t->live + 1) * 2 > cap) cap *= 2;       /* mostly live: grow */
        rehash(t, cap);                              /* else: purge tombstones */
        i = probe(t, key, &found);
    }
    if (t->state[i] == EMPTY) t->used++;
    t->state[i] = FULL;
    t->keys[i] = key;
    t->vals[i] = 0;
    t->live++;
    return &t->vals[i];
}

static int64_t *get(const table *t, uint64_t key) {
    int found;
    size_t i = probe(t, key, &found);
    return found ? &t->vals[i] : NULL;
}

static int del(table *t, uint64_t key) {
    int found;
    size_t i = probe(t, key, &found);
    if (!found) return 0;
    t->state[i] = TOMB;                              /* keep probe chains intact */
    t->live--;
    return 1;
}

int main(void) {
    table t;
    init(&t, 8);
    for (uint64_t i = 0; i < 1000000; i++)
        (*upsert(&t, (i * i) % 1000))++;             /* count residues of squares */
    del(&t, 0);
    int64_t *one = get(&t, 1);
    printf("distinct=%zu cap=%zu count(1)=%lld has(0)=%d\n",
           t.live, t.cap, (long long)(one ? *one : 0), get(&t, 0) != NULL);
    free(t.keys); free(t.vals); free(t.state);
    return 0;
}

It prints distinct=158 cap=256 count(1)=8000 has(0)=0. Python gives the same numbers, 159 residues minus the deleted one and 8000 squares ending in 001.

This block, extracted from the post, compiles cleanly with -Wall -Wextra -Wpedantic. A test built with -fsanitize=address,undefined includes the same file:

  • 2,000,000 random upserts and deletes on 4096 keys that differ only above bit 40, checked against a plain array.
  • 999,900 delete-then-insert rounds with 100 live keys. Capacity stayed at 256, and absent-key lookups never hung.
  • Deleting a key and upserting it twice gave one entry with count 2.
  • Growth after 3 deletes left no tombstones.

All passed. On an Apple M2 Pro at -O2, 10 million upserts over about a million distinct keys took 0.15 s, or 15 ns each. With every key shifted left by 32 it took 17 ns each. When I changed slot_of to key & (cap - 1), inserting 20,000 keys shifted left by 32 took 0.27 s against 0.0002 s.

What libraries ship

GLib’s GHashTable (2.88.4) uses power-of-two arrays, but computes the index as (hash * 11) % mod, where mod is a prime just below the size. It probes quadratically and stores each entry’s full hash. Tombstones are hash value 1. It resizes above 15/16 occupancy, counting tombstones, or below 1/4 live. Its docs warn that GLib’s own hash functions are “not particularly robust against manufactured keys that cause hash collisions”.

khash (klib, version 0.2.8) generates typed tables from macros. It keeps two flag bits per bucket for empty and deleted. The maximum load is 0.77. The default integer hash is the identity, and the index is hash & mask.

stb_ds (v0.98) groups slots into buckets of 8, probes quadratically over buckets, grows at 3/4, rebuilds when tombstones reach 3/16 and shrinks at 1/4. String keys get a rotate-and-add loop followed by Thomas Wang’s mix function. Other keys use a weakened SipHash unless you define STBDS_SIPHASH_2_4.

Curious facts

  • glibc’s hcreate allocates one slot more than the prime it picks, so index 0 is never used and the per-slot hash field doubles as the “used” flag.
  • Apple’s hcreate.c was written from man pages. A comment explains, “I tried to look at Knuth (as cited by the Solaris manual page), but nobody had a copy in the office, so…”
  • FreeBSD 15’s hcreate just returns 1. The table appears on the first hsearch.
  • Linux multiplies by 0x61C8864680B583EB, which is 2^64 minus 0x9E3779B97F4A7C15. Its comment says the negative “is very slightly easier to multiply by and makes no difference to the hash distribution.”

History

  • AT&T System V: hcreate, hdestroy and hsearch first appear (FreeBSD man page). POSIX derived them from SVID Issue 1.
  • glibc 2.0: Ulrich Drepper adds the hsearch family and the _r variants.
  • musl 0.7.11: the XSI <search.h> API. musl 1.1.0: the _r versions.
  • December 2015: FreeBSD replaces its chained hsearch with a resizable open-addressing table, FNV-1a and a random seed. The commit says a fixed size “often either wastes memory (table too big) or yields bad performance (table too small)”.

Sources

ls c/