Skip to content

Validate Before Converting

The Course
•
34 min study

fgets gives you text, and "25\n" is not the number 25. It is the characters '2', '5' and a newline. Turning text into a number is called parsing, and it is where input meets every rule from this week: bounds, overflow, pointers and unchanged output on failure. The old standard function atoi shows why care is needed. It returns 0 for text it cannot read, so "0" and "banana" look the same, and for a number too large for an int its behavior is undefined. The project's parser is small and strict instead: it says yes or no, and only writes a result when the answer is yes.

Predict and run

This one-digit parser is a simplified version of the real one. Predict both lines.

Predict before running C
#include <stdio.h>

int digit_minutes(const char *text, int *out) {
    if (text == NULL || out == NULL || text[0] < '1' || text[0] > '9') {
        return 0;
    }
    if (text[1] != '\0') {
        return 0;
    }
    *out = text[0] - '0';
    return 1;
}

int main(void) {
    int result = 7;
    int ok = digit_minutes("5", &result);
    printf("%d %d\n", ok, result);
    ok = digit_minutes("5x", &result);
    printf("%d %d\n", ok, result);
    return 0;
}
Check your prediction
Text
1 5
0 5

"5" passed both checks and stored 5. "5x" had a valid first character but something after it, so the function returned 0 without touching result, which kept the 5 from the first call. Try "": the first character is the terminator, which is not between '1' and '9', so the function rejects it before it ever looks at text[1]. The order of the checks protects the read.

The contract comes first

Before any code, the project fixes exactly which text counts as a duration:

  • One or more decimal digits, with a value from 1 through 180.
  • Optionally followed by one newline, since that is how fgets delivers a line.
  • Leading zeros are allowed, so "025" is 25.
  • Everything else is rejected: empty text, spaces, signs, letters after the digits, and any value out of range, however long.

A narrow format is a feature. Every rule is visible and testable, and nothing is guessed.

From a digit character to its value

The C standard guarantees that the characters '0' through '9' have consecutive codes. So ch - '0' turns a digit character into its value: '7' - '0' is 7 on every system. To build a number from several digits, multiply what you have so far by 10 and add the next digit. For "153" the value goes 1, then 15, then 153.

Reject before overflow can happen

Multiplying by 10 on every digit means that a 40-digit input would overflow an int long before the loop ends, and signed overflow is undefined. Checking the value after the multiplication is too late; the undefined operation has already happened. The project's parser checks before it multiplies, by asking whether value * 10 + digit would exceed 180, rearranged so the test itself cannot overflow: value > (MAX_MINUTES - digit) / 10. Once that is true, the function returns 0 at once. The value never goes above 180, whatever the input.

Read the real parser

This is parse_minutes from the project's report.c, with a small driver:

The project parser C
#include <stdio.h>
#define MAX_MINUTES 180

int parse_minutes(const char *text, int *out) {
    if (text == NULL || out == NULL || *text == '\0') {
        return 0;
    }
    int value = 0;
    int i = 0;
    while (text[i] >= '0' && text[i] <= '9') {
        int digit = text[i] - '0';
        if (value > (MAX_MINUTES - digit) / 10) {
            return 0;
        }
        value = value * 10 + digit;
        i++;
    }
    if (i == 0 || value < 1) {
        return 0;
    }
    if (text[i] == '\n') {
        i++;
    }
    if (text[i] != '\0') {
        return 0;
    }
    *out = value;
    return 1;
}

void try_parse(const char *text) {
    int minutes = -1;
    if (parse_minutes(text, &minutes)) {
        printf("%s -> %d\n", text, minutes);
    } else {
        printf("%s rejected, still %d\n", text, minutes);
    }
}

int main(void) {
    try_parse("025");
    try_parse("180");
    try_parse("181");
    try_parse("0");
    try_parse("25x");
    try_parse("99999999999999999999");
    return 0;
}
Text
025 -> 25
180 -> 180
181 rejected, still -1
0 rejected, still -1
25x rejected, still -1
99999999999999999999 rejected, still -1

Trace the stages: guard the pointers and empty text, consume digits with the overflow check, require at least one digit and a value of at least 1, allow one newline, then require the terminator. i == 0 catches text that starts with a non-digit, such as " 25" or "-1". Only the last line writes through out.

Practice

Exercise

Your turn

Write int parse_small(const char *text, int *out) using the same structure, for values 1 through 99, with an optional final newline and leading zeros allowed. On failure it returns 0 and leaves *out unchanged. Assert that "7", "42\n" and "099" are accepted with the right values, and that "", "0", "100", "4x", " 4", "-4" and "123456789012" are rejected, then print:

Text
Parse checks passed
Your workspace C
#include <stdio.h>
#include <assert.h>

int main(void) {
    int out = 55;
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Copy the stages, not just the loop: guards, digits with an overflow check against 99, at least one digit and a value of at least 1, an optional newline, then the terminator. The store goes last.

Hint 2: a first step

Start with one rejected case: set out to 55, call the parser on "abc\n", and assert both that the call fails and that out is still 55. Each further bad input is the same three lines with a different string.

Show one solution
C
#include <stdio.h>
#include <assert.h>

int parse_small(const char *text, int *out) {
    if (text == NULL || out == NULL) {
        return 0;
    }
    int value = 0;
    int i = 0;
    while (text[i] >= '0' && text[i] <= '9') {
        int digit = text[i] - '0';
        if (value > (99 - digit) / 10) {
            return 0;
        }
        value = value * 10 + digit;
        i++;
    }
    if (i == 0 || value < 1) {
        return 0;
    }
    if (text[i] == '\n') {
        i++;
    }
    if (text[i] != '\0') {
        return 0;
    }
    *out = value;
    return 1;
}

int main(void) {
    int out = 55;
    const char *bad[] = {"", "0", "100", "4x", " 4", "-4", "123456789012"};
    for (int i = 0; i < 7; i++) {
        int ok = parse_small(bad[i], &out);
        assert(!ok && out == 55);
    }
    int ok = parse_small("7", &out);
    assert(ok && out == 7);
    ok = parse_small("42\n", &out);
    assert(ok && out == 42);
    ok = parse_small("099", &out);
    assert(ok && out == 99);
    printf("Parse checks passed\n");
    return 0;
}
Text
Parse checks passed

The empty string needs no separate check here, because the digit loop runs zero times and i == 0 rejects it. The overflow test stops "123456789012" at the third digit, so value never exceeds 99. Every rejected case is checked against the unchanged 55, which is the promise a caller relies on. Next you will store the parsed values in a collection that refuses to grow past its capacity.

Was this article helpful?

Your response is saved on this device.