Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 11 min read
Open in the interactive handbook

76д. A hash table without malloc: open addressing, tombstones, FNV-1a and a console command table

Binary search from 76 finds a key in log n steps, but requires a sorted array: every insertion is a shift. A hash table finds a key in one or two probes on average and inserts just as fast. On a computer it is built from lists on the heap; in firmware — in one static array, without malloc, with open addressing. Here is how to arrange it, which hash to choose, why deletion is harder than it seems, and three typical uses: a console command table, a CAN identifier cache and filtering out repeated packets.

Basis: alg.c with the table, hashes and the command index built with gcc 12.2.0 on the computer (stm-sys:1): the search length at different fill levels is averaged over 50 tables, deletion is checked by 5000 "delete — insert" cycles, the hashes — on three sets of identifiers. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — function sizes. Work is measured by the number of probes — how many cells were looked at, not cycles.

Terms used in the documentation

Original Meaning
hash table hash table: key → cell number through a hash function
open addressing open addressing: all keys in one array, no lists
linear probing linear probing: occupied — look at the next cell
probe sequence, probe count the chain of probes, the number of cells looked at
load factor α load factor: keys / cells
tombstone tombstone: a mark "a deleted key was here"
backward-shift deletion deletion with a backward shift, without tombstones
FNV-1a the Fowler–Noll–Vo hash: XOR with a byte, then a multiplication
multiplicative hashing multiplicative hash: the high bits of a product with a constant

In plain words. Imagine a cabinet with numbered compartments. Instead of searching for an item in all compartments, the compartment number is computed straight from the item's name — that is the hash. If the compartment is occupied by someone else's item, you put it in the next free one, and when searching you also start from the computed compartment and go right. As long as the cabinet is less than half full, the item is almost always found on the first or second try.


76д.1 Why a hash table in firmware

Method Search Insertion Memory beyond the keys
scanning the array n/2 on average 1 none
binary search over a sorted array (76) log₂ n a shift of up to n elements none
hash table, filled up to 50 % 1–2 probes 1–2 probes twice as many cells as keys

A hash table trades memory for time: it needs a reserve of empty cells. In firmware this is justified when searches are frequent and on the fast path — in CAN frame reception, in command parsing, in a packet filter. If there are a dozen keys and they are known at build time, a sorted array in flash or a prefix tree (76ж) is simpler.


76д.2 Open addressing and linear probing

The whole table is two arrays: keys and values. An empty cell is marked with a key that never occurs in the data:

#define HT_BITS 8
#define HT_CAP (1u << HT_BITS)   /* степень двойки: остаток — это маска */
#define HT_EMPTY 0xFFFFFFFFu     /* ключ, которого не бывает */
#define HT_TOMB 0xFFFFFFFEu      /* надгробие: здесь был удалённый ключ */
typedef struct {
    uint32_t key[HT_CAP];
    uint16_t val[HT_CAP];
    uint16_t used, tombs;
} ht_t;

256 cells of 4 + 2 bytes and two counters — 1540 bytes of RAM. A search starts at the cell given by the hash and goes right around the circle until it finds the key or an empty cell:

int ht_find(const ht_t *t, uint32_t k)
{
    unsigned i = HT_HASH(k) & (HT_CAP - 1);
    for (unsigned n = 0; n < HT_CAP; n++) {
        PROBE_HOOK();
        if (t->key[i] == k)
            return (int)i;
        if (t->key[i] == HT_EMPTY)
            return -1; /* пустая ячейка обрывает цепочку */
        i = (i + 1) & (HT_CAP - 1);
    }
    return -1;
}

The size is a power of two so that the remainder of division is a mask: M0 has no division instruction, and % would cost a library call. Linear probing is the simplest and the most memory-friendly: neighbouring cells lie next to each other. Its weakness is that keys stick together in long runs, and so the table must not be filled to the top. ht_put always leaves at least one empty cell — otherwise a search for a missing key would not stop before a full circle. PROBE_HOOK is empty in firmware, on the computer it counts probes.


76д.3 The hash function: FNV-1a, multiplication and a mask

A hash must scatter similar keys to different cells. For strings and arbitrary bytes FNV-1a is convenient — two operations per byte:

uint32_t fnv1a_str(const char *s)
{
    uint32_t h = 2166136261u;
    while (*s) {
        h ^= (uint8_t)*s++;
        h *= 16777619u;
    }
    return h;
}

On the bench FNV-1a of the empty string is 811c9dc5, of the string "a" e40c292c, of "foobar" bf9cf968: that is how it is checked after moving to a new compiler. On M4 the function is 36 bytes, the multiplication is one instruction.

For integer keys — for example, CAN identifiers — there are two more candidates: just take the low bits (a mask) or multiply by 2³²/φ = 2654435769 and take the high bits (a multiplicative hash). The run: 64 identifiers in a table of 256 cells, the average and the largest search length:

Set of identifiers mask multiplication FNV-1a
consecutive: 0x100…0x13F 1.00 / 1 1.00 / 1 1.00 / 1
with a step of 256: 0x100, 0x200, … 32.50 / 64 1.02 / 2 1.00 / 1
random 29-bit 1.19 / 3 1.19 / 3 1.17 / 3

A mask is good as long as the low bits differ. But identifiers with a step of 256 have the same low 8 bits, and all 64 keys landed in one cell: the average search is 32.5 probes, the worst 64, essentially a scan. Multiplication and FNV-1a do not notice such a set. The rule: take a mask only if you know for sure that the low bits of the keys differ; otherwise multiplication (one instruction) or FNV-1a.


76д.4 The load factor

The fuller the table, the longer the chains. A run on random keys, the average over 50 tables of 256 cells:

Load α keys successful search: average successful: worst unsuccessful: average unsuccessful: worst
0.25 64 1.17 8 1.39 11
0.50 128 1.49 14 2.45 23
0.75 192 2.37 69 7.52 81
0.90 230 4.52 150 30.05 176

A graph: horizontally the load α from 0 to 1, vertically probes per search; the run's points for successful and unsuccessful search at 0.25, 0.50, 0.75 and 0.90 and dashed estimates for a large table; unsuccessful search takes 1.39, 2.45, 7.52 and 30.05 probes

The dashed lines are the well-known estimates for linear probing in a large table: ½(1 + 1/(1 − α)) probes for a successful search and ½(1 + 1/(1 − α)²) for an unsuccessful one. At α = 0.75 the estimate for an unsuccessful search is 8.5 probes, the run gave 7.52; at 0.9 a table of 256 cells is noticeably better than the estimate, but the worst case — 176 probes — is already almost a scan. For firmware the boundary is simple: no more than 50–70 %. At 50 % the average unsuccessful search is 2.45 probes.


76д.5 Deletion: tombstones and shifting

You cannot just clear a cell: it may have been a link in someone's chain, and the search for a key lying further on would stop at it. The usual solution is a tombstone: the cell is marked "a key was here", the search goes through it further, and an insertion may take it.

The run: the table is half full (128 keys), 5000 times a random key is deleted and a new one inserted. With tombstones there were 128 of them by the end — the entire free part of the table. The unsuccessful search went up from 2.45 to 127.93 probes — almost no empty cells that stop a search were left — and starting from the 717th cycle insertions began to fail: 40 failures during the run, and those keys are lost. Tombstones are taken again only if they happen to be on the insertion's path, not where they lie.

There are two cures. The first is to rebuild the table periodically into a second array, but a small chip has no second array. The second — for linear probing — is backward-shift deletion: after the deleted key its run is scanned, and every key that can be moved closer to its "home" cell moves into the hole:

for (;;) {
    j = (j + 1) & (HT_CAP - 1);
    if (t->key[j] == HT_EMPTY)
        break;
    unsigned home = HT_HASH(t->key[j]) & (HT_CAP - 1);
    /* ключ из j можно перенести в дыру, если его «дом» не лежит между дырой и j */
    if (((j - home) & (HT_CAP - 1)) >= ((j - hole) & (HT_CAP - 1))) {
        t->key[hole] = t->key[j];
        t->val[hole] = t->val[j];
        hole = j;
    }
}
t->key[hole] = HT_EMPTY;

The same run with shifting: 0 tombstones, all 128 keys in place, an unsuccessful search takes 2.48 probes, as in a fresh table. The price is 136 bytes of code on M4 against 84 for deletion with a tombstone and slightly more work on deletion.


76д.6 A console command table

The console commands — names and handlers — live in flash as a const array. The hash index is built once at startup in RAM: 32 bytes for 16 commands, each cell holds the command number plus one:

void cmd_index_build(const cmd_t *cmds, unsigned n)
{
    memset(cmd_idx, 0, sizeof cmd_idx);
    for (unsigned c = 0; c < n; c++) {
        unsigned i = fnv1a_str(cmds[c].name) & (CMD_SLOTS - 1);
        while (cmd_idx[i])
            i = (i + 1) & (CMD_SLOTS - 1);
        cmd_idx[i] = (uint8_t)(c + 1);
    }
}

A lookup hashes the typed word, walks the chain and compares strings with strcmp only for candidates. With 16 commands in 32 cells — on average 1.13 probes, the worst is 3. The unknown command "reboot" landed in an empty cell: zero probes and not a single strcmp. A scan of the array would make 16 string comparisons for every operator mistake.

For a set known at build time the index can be computed in advance and also put in flash; and if the commands are parsed by prefix (like AT commands), a prefix tree from 76ж is more convenient.


76д.7 A CAN identifier cache

A gateway or a logger receives frames with hundreds of different identifiers, and for each frame it must quickly find "what to do with it": a buffer number, a scale, the last counter. The key is an 11- or 29-bit identifier, that is a uint32_t, the value is the record number in its own table. This is exactly ht_t from 76д.2 with a multiplicative hash. The table from 76д.3 matters: CAN identifiers often come in groups with the same low bits — one device takes 0x18FF0100, 0x18FF0200, … — and a mask degenerates into a scan on them.

The size is chosen from the number of identifiers with a twofold reserve: for 64 identifiers — 128 cells, 772 bytes.


76д.8 Filtering out repeated packets

In a mesh network (BLE mesh, LoRa with relaying) the same packet arrives several times through different neighbours. A node must relay it once. The key is the pair (source, packet number) packed into 32 bits; the table keeps the last 32 received keys, the oldest is evicted by backward-shift deletion — tombstones would pile up continuously here.

The run: 2000 packets from 8 sources, 566 of them repeats. 544 were filtered out — exactly as many repeats as arrived while the original was still among the last 32; the other 22 repeats were more than 32 packets late and would pass as new ones. The window is chosen from the worst repeat delay in the network, not the average.

Code of the whole table on M4: ht_find — 68 bytes, ht_put — 160, ht_del_shift — 136.


76д.9 Pitfalls

The search looped forever. The table was filled to the top, no empty cells were left, and a search for a missing key goes round the circle. Always leave at least one empty cell, and better keep the load at 50–70 %.

A key disappeared after its neighbour was deleted. The deleted cell was simply cleared, and the chain broke. A tombstone or backward-shift deletion.

After a week of operation the table "slows down" and loses keys. Tombstones piled up: in the run — 128 of them, an unsuccessful search of 127.93 probes, 40 insertion failures. Backward-shift deletion or a rebuild.

All identifiers in one cell. The hash is a mask of the low bits, and the keys have the same low bits: a step of 256 gave 32.5 probes on average. A multiplicative hash or FNV-1a.

% instead of a mask on M0. The table size is not a power of two, and every search calls a library division. The size is a power of two.

An empty cell is marked with zero, and zero is a real key. The identifier 0x000 exists. The mark is a value that certainly does not occur in the data (here 0xFFFFFFFF with 29-bit keys).


76д.10 Summary

Next: section 76е "Linked lists on a static pool: intrusive lists, a node pool and container_of" — how to keep objects in several lists at once without a heap and remove them from the middle with four pointer writes.

Open in the interactive handbook