ZetCode

Hash tables in K&R C

last modified December 5, 2026 K&R C 1978

A hash table finds a name without searching through all the names. A hash function turns the name into a number, the index of a bucket in an array, and the name is stored in that bucket. Different names can land in the same bucket, so each bucket holds a linked list, a chain, of the names that hash to it. The book builds such a table for the names and replacement texts of #define lines, the core of a macro processor. This article builds it step by step, starting with the hash function.

Hashing a string

The simplest hash function adds up the character codes of the string and takes the remainder after dividing by the number of buckets, so the result is always a valid index.

hashsum.c
#include <stdio.h>

#define HASHSIZE 100

/* add up the characters of s */
int hash(s)
char *s;
{
    int h;

    for (h = 0; *s != '\0'; s++)
        h += *s;
    return h % HASHSIZE;
}

int main()
{
    static char *words[] = {
        "int", "char", "while", "stop", "pots", "tops", "spot", NULL
    };
    char **p;

    for (p = words; *p != NULL; p++)
        printf("%-6s %2d\n", *p, hash(*p));
    return 0;
}

hash walks the string with a pointer and adds each character to h. The table has 100 buckets, so the result is between 0 and 99. The words are kept in an array of pointers that ends with a null pointer.

$ gcc -std=c89 -pedantic -Wall -Wextra -o hashsum hashsum.c
$ ./hashsum
int    31
char   14
while  37
stop   54
pots   54
tops   54
spot   54

The four words with the letters s, t, o, and p all land in bucket 54. A sum does not depend on the order of the characters, so every rearrangement of the same letters collides, and names such as x1 and y0 collide too.

Spreading the names

A better function lets the order matter. It multiplies the value so far by a small odd number before it adds the next character, so each character moves the earlier ones around. The next program compares both functions on a thousand generated names.

chains.c
#include <stdio.h>

#define HASHSIZE 101
#define NNAMES   1000

unsigned sumhash(s)     /* the sum of the characters */
char *s;
{
    unsigned h;

    for (h = 0; *s != '\0'; s++)
        h += *s;
    return h % HASHSIZE;
}

unsigned mulhash(s)     /* each character multiplies the rest */
char *s;
{
    unsigned h;

    for (h = 0; *s != '\0'; s++)
        h = *s + 31 * h;
    return h % HASHSIZE;
}

/* hash the names item0...item999 and count the chain lengths */
int report(title, hash)
char *title;
unsigned (*hash)();
{
    int count[HASHSIZE], i, empty, longest;
    char name[20];

    for (i = 0; i < HASHSIZE; i++)
        count[i] = 0;
    for (i = 0; i < NNAMES; i++) {
        sprintf(name, "item%d", i);
        count[(*hash)(name)]++;
    }
    empty = longest = 0;
    for (i = 0; i < HASHSIZE; i++) {
        if (count[i] == 0)
            empty++;
        if (count[i] > longest)
            longest = count[i];
    }
    printf("%s: %d empty buckets, longest chain %d\n", title, empty, longest);
    return 0;
}

int main()
{
    printf("item99: %u %u\n", sumhash("item99"), mulhash("item99"));
    report("sum", sumhash);
    report("multiply", mulhash);
    return 0;
}

Both functions compute with unsigned values, which wrap around instead of overflowing when the product gets too large. The table has 101 buckets, a prime number, which helps the remainder use all the bits of the hash. report receives the hash function as a pointer, builds the names item0 to item999 with sprintf, and counts how many land in each bucket. With 1000 names in 101 buckets, an even spread would put about ten names in each.

$ gcc -std=c89 -pedantic -Wall -Wextra -o chains chains.c
$ ./chains
item99: 40 53
sum: 56 empty buckets, longest chain 71
multiply: 0 empty buckets, longest chain 13

The names differ only in their digits, and the sum of their characters falls in a narrow range, so the sum leaves more than half of the buckets empty and puts 71 names in one chain. Multiplying fills every bucket, and no chain is longer than 13.

On the PDP-11, an unsigned has 16 bits, so the products wrap around at 65536 instead of 4294967296. The sums are small and stay the same, but the multiplying function gives other values: item99 lands in bucket 96 instead of 53. The names go to other buckets, and they are spread just as evenly. A table written to a file by one machine cannot be read with the hash function of the other.

$ cc chains.c
$ a.out
item99: 40 96
sum: 56 empty buckets, longest chain 71
multiply: 0 empty buckets, longest chain 13

Lookup and install

The table itself is an array of pointers to the first entries of the chains. Each entry holds a name, its replacement text, and a pointer to the next entry of the chain. The table goes into a file of its own, with a header for the programs that use it.

table.h
#define HASHSIZE 101

struct nlist {          /* an entry of the table */
    char *name;
    char *def;
    struct nlist *next; /* the next entry in the chain */
};

struct nlist *lookup(), *install();

The header defines the size of the table and the entry, and declares the two functions that return pointers to entries.

table.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "table.h"

struct nlist *hashtab[HASHSIZE];        /* the chains */

unsigned hash(s)
char *s;
{
    unsigned h;

    for (h = 0; *s != '\0'; s++)
        h = *s + 31 * h;
    return h % HASHSIZE;
}

struct nlist *lookup(s)         /* find s in the table */
char *s;
{
    struct nlist *np;

    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
            return np;
    return NULL;
}

char *strsave(s)
char *s;
{
    char *p;

    if ((p = malloc(strlen(s) + 1)) != NULL)
        strcpy(p, s);
    return p;
}

/* put name and def in the table; a new def replaces the old one */
struct nlist *install(name, def)
char *name, *def;
{
    struct nlist *np;
    unsigned h;

    if ((np = lookup(name)) == NULL) {
        np = (struct nlist *) malloc(sizeof(struct nlist));
        if (np == NULL || (np->name = strsave(name)) == NULL)
            return NULL;
        h = hash(name);
        np->next = hashtab[h];          /* in front of the chain */
        hashtab[h] = np;
    } else
        free(np->def);
    if ((np->def = strsave(def)) == NULL)
        return NULL;
    return np;
}

hashtab is external, so its pointers start as null pointers: every chain is empty. lookup hashes the name and walks only its chain, comparing names with strcmp. install looks the name up first. A new name gets an entry, which goes in front of its chain, where it can be linked in without walking the chain. For a name that is already there, the old text is freed and replaced. Both the name and the text are copied with strsave, because the caller's strings may change later. install returns NULL if it runs out of memory.

defs.c
#include <stdio.h>
#include "table.h"

int show(name)
char *name;
{
    struct nlist *np;

    if ((np = lookup(name)) != NULL)
        printf("%s = %s\n", name, np->def);
    else
        printf("%s is not defined\n", name);
    return 0;
}

int main()
{
    install("MAXLINE", "1000");
    install("EOF", "(-1)");
    install("YES", "1");
    install("NO", "0");
    show("MAXLINE");
    show("EOF");
    show("MAYBE");
    install("MAXLINE", "100");
    show("MAXLINE");
    return 0;
}

The program installs four names, looks up three of them, one of which was never installed, and then gives MAXLINE a new value.

$ gcc -std=c89 -pedantic -Wall -Wextra -o defs defs.c table.c
$ ./defs
MAXLINE = 1000
EOF = (-1)
MAYBE is not defined
MAXLINE = 100

Removing a name

A macro processor also needs #undef, which removes a name from the table. The entry must be unlinked from its chain, like a node from a linked list.

undef.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "table.h"

extern struct nlist *hashtab[];
unsigned hash();

/* remove name from the table; return 1 if it was there */
int undef(name)
char *name;
{
    struct nlist *np, *prev;
    unsigned h;

    h = hash(name);
    prev = NULL;
    for (np = hashtab[h]; np != NULL; np = np->next) {
        if (strcmp(name, np->name) == 0)
            break;
        prev = np;
    }
    if (np == NULL)
        return 0;
    if (prev == NULL)
        hashtab[h] = np->next;  /* the first entry of the chain */
    else
        prev->next = np->next;
    free(np->name);
    free(np->def);
    free((char *) np);
    return 1;
}

int main()
{
    install("YES", "1");
    install("NO", "0");
    printf("undef YES: %d\n", undef("YES"));
    printf("undef YES: %d\n", undef("YES"));
    printf("YES %s, NO %s\n", lookup("YES") != NULL ? "defined" : "undefined",
        lookup("NO") != NULL ? "defined" : "undefined");
    return 0;
}

undef needs the array and the hash function of table.c, so it declares them with extern and as a function returning unsigned. It walks the chain of the name, keeping the previous entry. The first entry of a chain is unlinked by changing the pointer in hashtab, any other by changing the next member of the entry before it. Then the two strings and the entry are freed. The second undef("YES") finds nothing and returns 0.

$ gcc -std=c89 -pedantic -Wall -Wextra -o undef undef.c table.c
$ ./undef
undef YES: 1
undef YES: 0
YES undefined, NO defined

A #define processor

With lookup and install, a simple macro processor takes only a few more lines. It reads its input line by line. A line that starts with #define puts a name and its text into the table; in every other line, each name that is in the table is replaced by its text.

macro.c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "table.h"

#define MAXLINE 200

int get_line(s, lim)
char s[];
int lim;
{
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
        s[i] = c;
    s[i] = '\0';
    return c == EOF && i == 0 ? EOF : i;
}

/* copy the identifier at s into name; return the end of it */
char *ident(s, name)
char *s, *name;
{
    while (isalnum(*s) || *s == '_')
        *name++ = *s++;
    *name = '\0';
    return s;
}

/* store #define lines in the table, replace names in other lines */
int main()
{
    char line[MAXLINE], name[MAXLINE], *s;
    struct nlist *np;

    while (get_line(line, MAXLINE) != EOF) {
        if (strncmp(line, "#define ", 8) == 0) {
            s = ident(line + 8, name);
            while (*s == ' ')
                s++;
            install(name, s);
            continue;
        }
        for (s = line; *s != '\0'; )
            if (isalpha(*s) || *s == '_') {
                s = ident(s, name);
                np = lookup(name);
                printf("%s", np != NULL ? np->def : name);
            } else
                putchar(*s++);
        putchar('\n');
    }
    return 0;
}

get_line reads a line without its newline and returns EOF at the end of the input. ident copies the letters, digits, and underscores at s into name and returns a pointer to the first character after them. strncmp(s, t, n) compares like strcmp, but at most n characters, so it tells whether the line starts with #define and a blank. For such a line, the name follows the keyword, and the rest of the line after the blanks is the text. In other lines, main copies the characters to the output, and each name is looked up and replaced if it is defined. A second #define of a name replaces its text from then on.

source.txt
#define MAXLINE 1000
#define YES 1
#define NO 0
char line[MAXLINE];
int found = NO;
if (len > MAXLINE) found = YES;
#define MAXLINE 80
char buf[MAXLINE]; /* NO MAXLINE here */

The input defines three names, uses them, and then changes MAXLINE.

$ gcc -std=c89 -pedantic -Wall -Wextra -o macro macro.c table.c
$ ./macro < source.txt
char line[1000];
int found = 0;
if (len > 1000) found = 1;
char buf[80]; /* 0 80 here */

The names in the comment are replaced as well: the program knows nothing about comments or strings. The C preprocessor removes the comments before it replaces names, and it leaves names inside strings alone.

Source

Dennis Ritchie: C Reference Manual (1975)

Hash table on Wikipedia

In this article we have built hash tables in K&R C: a hash function that adds the characters and one that multiplies, chain lengths on GCC and on the PDP-11, a chained table with lookup and install, removing a name, and a small #define processor. The next article turns to text processing.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.