Show contents
Chapter 6 of 7 · 25 min
Final project: counting the words of a text
By the end of this chapter, you'll be able to
- Read input of unknown size character by character with getchar
- Reuse a hash table to count occurrences
- Sort results with qsort and a comparison function
- Guarantee no overflow and no leak on untrusted input
Step 1: the design
- Reading:
getchar()reads one character at a time, untilEOF(the end of the input). A word is a run of letters; anything else (spaces, punctuation) ends it. - Bounds: a word longer than 31 characters is truncated, never written beyond the array.
- Counting: a hash table
word → count, whose entries hold their own copy of the word. - Ranking: we gather the entries into an array, sorted by decreasing count, then alphabetically on a tie, for a reproducible result.
- Clean-up: everything that was allocated is freed.
Accented letters are encoded in UTF-8 on several bytes, all above 127. We treat them as letters: café stays a single word.
The top three are displayed, then all the memory is freed.
Text description of the animation
- The characters arrive one by one.
- The letters build up in lowercase; the space ends the word.
- The word is looked up in the table: missing, it's added with count 1.
- On each new occurrence, its count goes up.
- At the end of the input, the entries are sorted.
- The top three are displayed, then all the memory is freed.
Step 2: the program
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NB_BUCKETS 64
#define WORD_MAX 32
typedef struct Entry {
char word[WORD_MAX];
int count;
struct Entry *next;
} Entry;
typedef struct {
Entry *buckets[NB_BUCKETS];
int distinct;
} Counter;
static unsigned long hash(const char *s) {
unsigned long h = 5381;
for (; *s != '\0'; s++) {
h = h * 33 + (unsigned char)*s;
}
return h;
}
static void counter_init(Counter *c) {
for (int i = 0; i < NB_BUCKETS; i++) {
c->buckets[i] = NULL;
}
c->distinct = 0;
}
static int counter_add(Counter *c, const char *word) {
unsigned long i = hash(word) % NB_BUCKETS;
for (Entry *e = c->buckets[i]; e != NULL; e = e->next) {
if (strcmp(e->word, word) == 0) {
e->count++;
return 0;
}
}
Entry *e = malloc(sizeof *e);
if (e == NULL) return -1;
snprintf(e->word, sizeof e->word, "%s", word);
e->count = 1;
e->next = c->buckets[i];
c->buckets[i] = e;
c->distinct++;
return 0;
}
static void counter_free(Counter *c) {
for (int i = 0; i < NB_BUCKETS; i++) {
Entry *e = c->buckets[i];
while (e != NULL) {
Entry *next = e->next;
free(e);
e = next;
}
c->buckets[i] = NULL;
}
}
static int compare(const void *a, const void *b) {
const Entry *x = *(const Entry *const *)a;
const Entry *y = *(const Entry *const *)b;
if (x->count != y->count) return y->count - x->count;
return strcmp(x->word, y->word);
}
static int is_letter(int ch) {
return isalpha(ch) || ch >= 128; /* the UTF-8 bytes of accented letters count as letters */
}
int main(void) {
Counter c;
counter_init(&c);
char word[WORD_MAX];
int length = 0;
long total = 0;
int ch;
int error = 0;
do {
ch = getchar();
if (ch != EOF && is_letter(ch)) {
if (length < WORD_MAX - 1) {
word[length++] = (char)tolower(ch);
}
} else if (length > 0) {
word[length] = '\0';
if (counter_add(&c, word) != 0) {
error = 1;
break;
}
total++;
length = 0;
}
} while (ch != EOF);
Entry **all = error ? NULL : malloc((size_t)c.distinct * sizeof *all + 1);
if (all == NULL) {
counter_free(&c);
return 1;
}
int k = 0;
for (int i = 0; i < NB_BUCKETS; i++) {
for (Entry *e = c.buckets[i]; e != NULL; e = e->next) {
all[k++] = e;
}
}
qsort(all, (size_t)k, sizeof *all, compare);
printf("%ld words, %d different\n", total, c.distinct);
for (int i = 0; i < k && i < 3; i++) {
printf("%-8s %d\n", all[i]->word, all[i]->count);
}
free(all);
counter_free(&c);
return 0;
}
The river flows, the river sings.
The fisher waits for the evening on the river.
15 words, 9 different
the 5
river 3
evening 1
The tricky points:
- The
do … whileloop also handles the last word when the input ends without a space or line break: on the pass wheregetcharreturnsEOF, the current word is still recorded. getcharreturns anint, not achar: it must be able to representEOF(a negative value) as well as the 256 possible bytes.qsortsorts any array: you give it the number of items, their size, and a function that compares two items through generic pointers (const void *). Here, the items areEntry *: we therefore receive pointers to pointers.- The
+ 1in themallocof theallarray: if the text contains no word at all,malloc(0)may returnNULLon some systems, which the program would take for an error. - If memory runs out, the program frees what it has already allocated before stopping.
Your turn
Worked exercise
Worked exercise: ignoring stop words
The most frequent words of a text are almost always "the", "a", "of"… Add a function int is_stop_word(const char *word) that returns 1 for the words the, a, an, of, on, in, and, for, to, at, and 0 otherwise. Test it on a few words, then say where to call it in the program so that these words aren't counted.
Hint 1
static const char *const STOP_WORDS[], and compare with strcmp in a loop.Hint 2
sizeof STOP_WORDS / sizeof STOP_WORDS[0] gives the number of items in the array, without counting them by hand.Show the solution and common mistakes
#include <stdio.h>
#include <string.h>
static const char *const STOP_WORDS[] = {"the", "a", "an", "of", "on", "in", "and", "for", "to", "at"};
int is_stop_word(const char *word) {
for (size_t i = 0; i < sizeof STOP_WORDS / sizeof STOP_WORDS[0]; i++) {
if (strcmp(word, STOP_WORDS[i]) == 0) return 1;
}
return 0;
}
int main(void) {
const char *tries[] = {"the", "river", "on", "evening", "for"};
for (int i = 0; i < 5; i++) {
printf("%s: %s\n", tries[i], is_stop_word(tries[i]) ? "ignored" : "counted");
}
return 0;
}
the: ignored
river: counted
on: ignored
evening: counted
for: ignored
In the program, the call goes just before counter_add: if (!is_stop_word(word) && counter_add(&c, word) != 0). On the project's text, the ranking then becomes river 3, followed by the words that appear once.
Common mistakes:
- Comparing before putting the word in lowercase: "The", at the start of a sentence, wouldn't be recognised.
- Writing the array's size by hand (
i < 10): when you add a stop word, you forget to update the number, and the last one is never tested.
Summary
- 1getchar reads input of unknown size; its result goes in an int to tell EOF apart.
- 2Each word is bounded to its array's size: an enormous input never overflows.
- 3qsort sorts any array with a comparison function on const void *.
- 4A complete sort order (count then alphabet) makes the result reproducible.
- 5On every path, including on error, everything allocated is freed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.