Data Structures in C: A Dynamic Array, a Linked List and a Hash Table
Implement a growing array, a singly linked list and a chained hash table from scratch, test each with assertions under AddressSanitizer, and verify the hash table counts against Python.
In this lesson you will
- Write a dynamic array and a linked list
- Write a hash table with chaining
- Test with assertions under a sanitizer
- Verify counts independently
About 28 minutes
The containers that C does not give you
Other languages ship growing arrays, lists and dictionaries in their standard libraries. C ships none of them, so every C programmer builds them, and building them is the best way to understand memory. A dynamic array stores elements in one block and doubles the block when it fills, which lesson 5 showed. A singly linked list stores each element in its own node with a pointer to the next one, so insertion at the front is cheap and indexing is slow. A hash table maps keys to values by computing a number from the key, the hash, and using it to choose a slot. Different keys can land in the same slot, which is a collision, and the simplest cure is chaining: each slot holds a linked list of the entries that share it.
Three habits make such code reliable. Each structure has a clear owner that frees it, and a function that releases everything. Each function states what it does when memory runs out. And each structure comes with tests that exercise it, run under AddressSanitizer, so that an out-of-range access or a leak is reported immediately. The program below implements all three structures in under a hundred lines, tests their basic properties with assert, and uses the hash table to count the words of a weather log.
| Structure | Strength | Weakness |
|---|---|---|
| Dynamic array | Fast indexing, compact | Insertion in the middle is slow |
| Linked list | Cheap insertion at a known place | Slow indexing, an allocation per node |
| Hash table | Fast average lookup by key | No order; needs a good hash function |
#define _DEFAULT_SOURCE
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { int *v; size_t n, cap; } Vec;
static void vec_push(Vec *a, int x) {
if (a->n == a->cap) { a->cap = a->cap ? a->cap * 2 : 2; a->v = realloc(a->v, a->cap * sizeof *a->v); assert(a->v); }
a->v[a->n++] = x;
}
typedef struct Node { int value; struct Node *next; } Node;
static Node *list_push(Node *head, int x) { Node *n = malloc(sizeof *n); assert(n); n->value = x; n->next = head; return n; }
static Node *list_reverse(Node *head) { Node *prev = NULL; while (head) { Node *next = head->next; head->next = prev; prev = head; head = next; } return prev; }
static void list_free(Node *h) { while (h) { Node *n = h->next; free(h); h = n; } }
typedef struct Entry { char *key; int count; struct Entry *next; } Entry;
typedef struct { Entry *slot[16]; size_t items, collisions; } Table;
static unsigned hash(const char *s) { unsigned h = 5381; while (*s) h = h * 33 + (unsigned char)*s++; return h; }
static void table_inc(Table *t, const char *key) {
unsigned i = hash(key) % 16;
for (Entry *e = t->slot[i]; e; e = e->next) if (strcmp(e->key, key) == 0) { e->count++; return; }
Entry *e = malloc(sizeof *e); assert(e);
e->key = strdup(key); e->count = 1; e->next = t->slot[i];
if (t->slot[i]) t->collisions++;
t->slot[i] = e; t->items++;
}
static int table_get(const Table *t, const char *key) {
for (Entry *e = t->slot[hash(key) % 16]; e; e = e->next) if (strcmp(e->key, key) == 0) return e->count;
return 0;
}
static void table_free(Table *t) { for (int i = 0; i < 16; i++) for (Entry *e = t->slot[i]; e;) { Entry *n = e->next; free(e->key); free(e); e = n; } }
int main(void) {
Vec a = {0};
for (int i = 1; i <= 10; i++) vec_push(&a, i * i);
int sum = 0; for (size_t i = 0; i < a.n; i++) sum += a.v[i];
assert(a.n == 10 && sum == 385);
printf("dynamic array: %zu items, capacity %zu, sum of squares %d\n", a.n, a.cap, sum);
free(a.v);
Node *head = NULL;
for (int i = 1; i <= 5; i++) head = list_push(head, i);
int before[5], after[5], k = 0;
for (Node *n = head; n; n = n->next) before[k++] = n->value;
head = list_reverse(head);
k = 0; for (Node *n = head; n; n = n->next) after[k++] = n->value;
printf("linked list pushed 1..5 at the front: %d %d %d %d %d; after reverse: %d %d %d %d %d\n", before[0], before[1], before[2], before[3], before[4], after[0], after[1], after[2], after[3], after[4]);
assert(before[0] == 5 && after[0] == 1);
list_free(head);
Table t = {0};
char text[] = "rain sun wind rain fog sun sun cloud rain wind sun rain snow sun wind cloud fog rain sun hail";
int total = 0;
for (char *w = strtok(text, " "); w; w = strtok(NULL, " ")) { table_inc(&t, w); total++; }
printf("hash table: %d words, %zu distinct, %zu collisions in 16 slots\n", total, t.items, t.collisions);
const char *keys[] = {"sun", "rain", "wind", "fog", "cloud", "snow", "hail", "tornado"};
for (int i = 0; i < 8; i++) printf(" %s %d\n", keys[i], table_get(&t, keys[i]));
assert(table_get(&t, "tornado") == 0);
table_free(&t);
printf("all assertions passed\n");
return 0;
}
dynamic array: 10 items, capacity 16, sum of squares 385
linked list pushed 1..5 at the front: 5 4 3 2 1; after reverse: 1 2 3 4 5
hash table: 20 words, 7 distinct, 1 collisions in 16 slots
sun 6
rain 5
wind 3
fog 2
cloud 2
snow 1
hail 1
tornado 0
all assertions passed
All three structures passed their assertions, under AddressSanitizer and UndefinedBehaviorSanitizer, which stayed silent, so nothing leaked and no access was out of range. The dynamic array holds 10 items in a capacity of 16, doubling 2, 4, 8, 16, with a sum of squares of 385. The linked list, built by pushing 1 to 5 at the front, reads 5 4 3 2 1 from the head, which is the reverse of the insertion order, and after list_reverse it reads 1 2 3 4 5: the function rewires each node’s next pointer in one pass, with no allocation.
The hash table counted 20 words with 7 distinct ones, and 1 of them landed in an already occupied slot among the 16, which is what chaining is for. The counts are sun 6, rain 5, wind 3, fog 2, cloud 2, snow 1, hail 1, tornado 0, and an absent key, tornado, correctly gives zero. The hash function here is djb2, h = h x 33 + c starting at 5381, a simple string hash that works well in practice, though it is not designed for security.
To verify the hash table independently, the course counted the same words with Python’s collections.Counter, {‘cloud’: 2, ‘fog’: 2, ‘hail’: 1, ‘rain’: 5, ‘snow’: 1, ‘sun’: 6, ‘wind’: 3}, and got the same counts for every key. It also reimplemented the djb2 hash in Python, computed the slot of each distinct word modulo 16, and found 1 words that share a slot with an earlier one, the same number of collisions that the C program reported.
Check by hand: the squares 1, 4, 9, …, 100 add up to 385. The word list has 20 words, in which sun appears 6 times and rain 5, hail once, and the structure has 7 distinct words.
In each structure above, one function frees what the others allocate. Without that discipline, leaks and double frees appear. Run tests under AddressSanitizer to prove it.
After each operation, check what must always be true: the count equals the number of nodes, a reversed list reversed twice is the original, a counted word is found. assert makes these checks cheap.
Every program in this lesson was compiled with GCC 13 using -std=c17 -Wall -Wextra and run while the course was written. Compilers and platforms differ, so check your compiler’s documentation, and the C standard drafts, for details that the standard leaves open. strdup is POSIX, and C23 adds it to the standard. The program is built with AddressSanitizer and UndefinedBehaviorSanitizer.
Practice
Add a function that removes a key from the hash table and test that its count becomes zero and that nothing leaks. Resize the table when the number of items exceeds twice the number of slots. Add a doubly linked list and compare the cost of removing a node.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is a collision in a hash table?
- A crash
- A memory leak
- Two keys landing in the same slot
- A sorted list
Chaining stores them in a list.
What does list_reverse do?
- Copies the list
- Rewires the next pointers in one pass
- Sorts the list
- Frees the list
No allocation.
Why does the dynamic array double its capacity?
- Because C requires it
- To keep the number of reallocations small
- To use less memory
- To avoid free
Amortised cost.
What did the sanitizers report?
- Nothing: no leak or invalid access
- A leak
- An overflow
- A crash
The tests ran clean.
How was the hash table verified?
- By Python Counter on the same words
- By running it twice
- By trusting it
- It was not
Every count matched.
Summary
- C has no built-in containers, so you build them from arrays, pointers and malloc.
- A dynamic array doubles, a linked list links nodes, and a hash table chains collisions.
- Assertions under AddressSanitizer test structures and ownership.
- An independent counter verified the results.
Questions
Are linked lists good for performance?
Usually not on modern hardware, because each node is a separate allocation and the processor cache works best on contiguous memory. Dynamic arrays are the better default.
What is a good hash function?
One that spreads keys evenly and is fast. djb2 is a classic simple choice. For attacker-controlled keys, use a keyed hash such as SipHash.
Should I write my own containers?
In real projects consider a tested library first. Writing them once, as here, teaches you how memory and pointers work.
