Skip to content

Bounded Topic Tokens

The Course
•
45 min study

The analyzer's input format is one lowercase ASCII topic, whitespace, and a duration, such as reading 25. Each record stores its topic in a fixed array, char topic[24]. Now the input decides how many characters arrive, and the array cannot stretch. A line with a 40-letter topic must not write 40 letters into 24 bytes; that is a buffer overflow, the classic C security bug. It also must not quietly keep the first 23 letters, because two different long topics would then become the same stored name and their totals would merge. The safe answer is to measure first and reject a token that does not fit.

Predict and run

Read the program before pressing Run. Write down its output and explain why cats is refused.

Predict before running C
#include <stdio.h>

int copy_topic(const char *text, char out[4]) {
    size_t length = 0;
    while (text[length] >= 'a' && text[length] <= 'z') {
        if (length >= 3) { return 0; }
        ++length;
    }
    if (length == 0 || text[length] != '\0') { return 0; }
    for (size_t i = 0; i <= length; ++i) { out[i] = text[i]; }
    return 1;
}

int main(void) {
    char topic[4];
    printf("%d\n", copy_topic("cat", topic));
    if (copy_topic("cat", topic)) { puts(topic); }
    printf("%d\n", copy_topic("cats", topic));
    return 0;
}
Check your prediction
Text
1
cat
0

A 4-byte buffer holds 3 letters plus the terminator. On the fourth letter of cats, length is already 3, so the function returns 0 before copying anything. The copy loop uses i <= length on purpose: it copies the '\0' at text[length] too.

The terminator is part of the size

A C string is a sequence of bytes ending with a zero byte, '\0'. Functions such as printf("%s"), strlen and strcmp have no length parameter: they keep reading until they find that zero. A buffer of 24 bytes therefore holds at most 23 visible characters. If you copy 23 letters and forget the terminator, the array looks fine in a debugger, but printf continues into whatever bytes follow it. That is an out-of-bounds read and undefined behavior.

The parameter char out[4] is really char *out: array parameters decay to pointers, so the 4 is documentation only. The function must enforce the bound itself, which is why the course passes capacity explicitly from here on.

Why not strcpy or strncpy

strcpy(out, text) copies until it finds the terminator in text, however far that is. It has no idea how big out is:

C
char topic[4];
strcpy(topic, "catalog");   /* writes 8 bytes into 4: buffer overflow */

strncpy(out, text, n) looks safer, but when text is too long it copies n bytes and does not add a terminator, which leaves an unterminated array for the next printf to run past. And both functions accept any characters, so they do not validate the format.

snprintf always terminates (when the capacity is not 0) and tells you whether it had to cut the text: it returns the length it wanted to write, or a negative value on an encoding error. That makes truncation detectable, even though this format rejects it:

Detect truncation C
#include <stdio.h>
#include <string.h>

/* Returns 1 when text had to be cut to fit. */
int store(char *out, size_t capacity, const char *text) {
    int wanted = snprintf(out, capacity, "%s", text);
    return wanted < 0 || (size_t)wanted >= capacity;
}

int main(void) {
    char a[4];
    char b[4];
    int cut = store(a, sizeof a, "catalog");
    cut |= store(b, sizeof b, "category");
    printf("stored \"%s\" and \"%s\"\n", a, b);
    printf("same after truncation: %s\n", strcmp(a, b) == 0 ? "yes" : "no");
    printf("truncated: %s\n", cut ? "yes" : "no");
    return 0;
}
Text
stored "cat" and "cat"
same after truncation: yes
truncated: yes

Two different topics became one. In a report, their minutes would be added together without any error. Rejecting oversize tokens keeps different inputs different.

Characters are small integers

The check ch >= 'a' && ch <= 'z' relies on the lowercase letters being consecutive, which is true in ASCII, the encoding this format specifies. (C itself only guarantees that the digits '0' to '9' are consecutive.) You may know islower from <ctype.h>. It depends on the current locale, and it takes an int that must be either EOF or a value representable as unsigned char. Passing a plain char holding a byte above 127 can be negative on many platforms, which is undefined behavior. If you use <ctype.h>, write islower((unsigned char)ch). The explicit range check avoids both issues.

Read through a cursor

A record line has more than one field, so the parser walks through it with a pointer, the cursor. A token function receives the cursor's address, reads letters, and on success moves the cursor past them, so the next step starts where this one stopped. On failure, it leaves both the cursor and the output untouched: validate into locals, then commit.

The cursor is a const char *: a pointer to the next character to read. For a function to move it, the function needs the address of the caller's cursor, which is a pointer to a pointer, const char **. Two levels of * are easy to mix up, so here is a small function that only skips spaces:

Move a cursor through its address C
#include <stdio.h>

/* Moves *cursor past any spaces. Returns how many it skipped. */
int skip_spaces(const char **cursor) {
    const char *p = *cursor;
    int skipped = 0;
    while (*p == ' ') {
        ++p;
        ++skipped;
    }
    *cursor = p;
    return skipped;
}

int main(void) {
    const char *line = "   25 minutes";
    const char *cursor = line;
    printf("before: \"%s\", first char '%c'\n", cursor, *cursor);
    int skipped = skip_spaces(&cursor);
    printf("skipped %d\n", skipped);
    printf("after: \"%s\", first char '%c'\n", cursor, *cursor);
    printf("line still: \"%s\"\n", line);
    return 0;
}
Text
before: "   25 minutes", first char ' '
skipped 3
after: "25 minutes", first char '2'
line still: "   25 minutes"

Trace the names inside skip_spaces:

  • cursor is the address of main's variable cursor. The function never changes it.
  • *cursor is main's cursor itself, a const char * pointing into the line. Reading it gives the starting point; assigning to it moves the caller's cursor.
  • **cursor would be the character under the caller's cursor, ' ' at the start.

The function copies *cursor into a local p, walks p forward while it sees spaces, and writes the final position back with *cursor = p; once, at the end. That is validate-then-commit again: if this function could fail, it would return before that line, and the caller's cursor would not have moved. The line itself is never changed; only the caller's view of where reading continues.

Fix: the cursor that does not move

This version compiles and counts correctly, but the caller's cursor never moves. Find out why before you open the check.

Fix: the cursor that does not move C
#include <stdio.h>

/* Meant to move the caller's cursor past spaces. */
int skip_spaces(const char *cursor) {
    int skipped = 0;
    while (*cursor == ' ') {
        ++cursor;
        ++skipped;
    }
    return skipped;
}

int main(void) {
    const char *line = "   25 minutes";
    const char *cursor = line;
    int skipped = skip_spaces(cursor);
    printf("skipped %d\n", skipped);
    printf("after: \"%s\"\n", cursor);
    return 0;
}
Check your fix

skip_spaces receives a copy of main's pointer. ++cursor moves the copy, which disappears when the function returns, so main still prints the spaces. To move the caller's cursor, pass its address and write through it:

C
#include <stdio.h>

/* Moves *cursor past any spaces. Returns how many it skipped. */
int skip_spaces(const char **cursor) {
    const char *p = *cursor;
    int skipped = 0;
    while (*p == ' ') {
        ++p;
        ++skipped;
    }
    *cursor = p;
    return skipped;
}

int main(void) {
    const char *line = "   25 minutes";
    const char *cursor = line;
    int skipped = skip_spaces(&cursor);
    printf("skipped %d\n", skipped);
    printf("after: \"%s\"\n", cursor);
    return 0;
}
Text
skipped 3
after: "25 minutes"

read_topic below works the same way, with one more job: it may fail, and then neither the cursor nor the output may change.

Practice

Exercise

Your turn

Write int read_topic(const char **cursor, char out[], size_t capacity). It reads lowercase letters starting at *cursor. It fails if there are no letters, if they need more than capacity - 1 bytes, or if the next character is neither a space nor '\0'. On success it copies the letters with a terminator, moves *cursor to the first character after them, and returns 1. On failure it returns 0 and changes neither *cursor nor out. With capacity 8, the starter must print: "reading 25": ok "reading", rest " 25", "Reading 25": rejected, "readings 1": rejected, "math": ok "math", rest "", "abc1": rejected.

Your workspace C
#include <stdio.h>
#include <stddef.h>

/* Write read_topic here. */

static void show(const char *line) {
    char topic[8] = "unset";
    const char *cursor = line;
    if (read_topic(&cursor, topic, sizeof topic)) {
        printf("\"%s\": ok \"%s\", rest \"%s\"\n", line, topic, cursor);
    } else {
        printf("\"%s\": rejected\n", line);
    }
}

int main(void) {
    show("reading 25");
    show("Reading 25");
    show("readings 1");
    show("math");
    show("abc1");
    return 0;
}
Hint 1: the idea

Measure before you copy. Count letters in a local, stop with failure the moment the count reaches capacity - 1 and another letter follows, then inspect the character after the letters.

Hint 2: a first step

Write the counting loop first and nothing else: count the letters at *cursor in a local, and print the count for each starter line instead of copying. Check reading gives 7 and readings would need 9 bytes. Then decide where the capacity test belongs in that loop, and where the separator check goes after it.

Show one solution
Run the solution C
#include <stdio.h>
#include <stddef.h>

int read_topic(const char **cursor, char out[], size_t capacity) {
    const char *p = *cursor;
    size_t length = 0;
    while (p[length] >= 'a' && p[length] <= 'z') {
        if (length + 1 >= capacity) { return 0; }
        ++length;
    }
    if (length == 0 || (p[length] != ' ' && p[length] != '\0')) { return 0; }
    for (size_t i = 0; i < length; ++i) { out[i] = p[i]; }
    out[length] = '\0';
    *cursor = p + length;
    return 1;
}

static void show(const char *line) {
    char topic[8] = "unset";
    const char *cursor = line;
    if (read_topic(&cursor, topic, sizeof topic)) {
        printf("\"%s\": ok \"%s\", rest \"%s\"\n", line, topic, cursor);
    } else {
        printf("\"%s\": rejected\n", line);
    }
}

int main(void) {
    show("reading 25");
    show("Reading 25");
    show("readings 1");
    show("math");
    show("abc1");
    return 0;
}
Text
"reading 25": ok "reading", rest " 25"
"Reading 25": rejected
"readings 1": rejected
"math": ok "math", rest ""
"abc1": rejected

readings has 8 letters and needs 9 bytes, so it is refused at the eighth letter, before any byte is written. reading needs exactly 8 and fits: testing both sides of the limit is what catches an off-by-one. The condition length + 1 >= capacity is written without subtracting from capacity, so it is safe even for capacity 0. The cursor now points at the separator, ready for the number, which is what the next lesson converts.

Was this article helpful?

Your response is saved on this device.