How to Validate Input in C- Free Online C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings

Validate Input in C

Prove that text really is the number you expect, using sscanf with %n, manual scanning and strtol.

Programs rarely fail because the logic is wrong. They fail because someone typed a letter where a number belongs. To validate input in C means proving that text is exactly the kind of value you expect before the rest of the program touches it. This lecture of our free C tutorial shows three practical techniques: sscanf with the %n specifier, a character-by-character scan, and strtol with proper error checks. They are the same habits professionals use in embedded C programming, where a console, a sensor or a radio link sends data nobody has vetted.

What You Will Learn

  • Why a successful sscanf call does not prove the whole input was a valid number
  • How to validate input in C using sscanf together with %n
  • How to check every character of a string by hand
  • How to use strtol with endptr and errno for range-safe conversion
  • How to design a small command parser that rejects bad lines cleanly

Prerequisites

Read the previous lecture on sscanf first. You also need arrays of char, the null terminator, pointers, and the ctype.h character-class functions such as isdigit. The code here is plain C17 and builds with any recent gcc or clang.

Why You Must Validate Input in C

Many beginners write scanf("%d", &x), see it work with 42, and move on. The trouble starts with everything else a user can type. The little program below feeds four different strings to sscanf with a plain %d.

#include <stdio.h>

int main(void)
{
    const char *inputs[] = { "13a", "42", "7.9", "abc" };
    const int count = (int)(sizeof inputs / sizeof inputs[0]);

    for (int i = 0; i < count; i++) {
        int v = -1;
        int n = sscanf(inputs[i], "%d", &v);
        printf("input \"%s\": sscanf returned %d, v = %d\n", inputs[i], n, v);
    }
    return 0;
}
input "13a": sscanf returned 1, v = 13
input "42": sscanf returned 1, v = 42
input "7.9": sscanf returned 1, v = 7
input "abc": sscanf returned 0, v = -1

Look at the first and third lines. The text 13a produced the number 13 and a perfectly happy return value of 1. The text 7.9 produced 7 and silently threw away .9. Only a string with no digits at the start was reported as a failure. If this value were a motor speed, a baud rate or a memory address, you would never know it was wrong.

Bad inputWhy a plain %d lets it through
13a%d stops at the letter and keeps 13
7.9%d stops at the dot and keeps 7
Empty lineDetected, but only if you look at the return value
99999999999Too big for int, behaviour is undefined
5000 where 0 to 255 is legalValid number, wrong range
Validate input in C: four gates before a value is trusted
raw text from UART / keyboard / file
Gate 1: sscanf returned exactly 1 ? (a number really starts the text)
Gate 2: text[used] is the null terminator ? (nothing left over)
Gate 3: value inside the allowed range ?
accept and useany gate fails: reject and report

Validate Input in C With sscanf and %n

The %n specifier is unusual. It does not read any characters and it is not counted in the return value. Instead it stores, through an int pointer, how many characters sscanf has consumed so far. If you put %n right after the conversion, you learn exactly where the number ended. Comparing that position with the end of the string tells you whether anything was left over.

How %n finds trailing junk: “13a” with %d%n
13aNUL
%d reads 13stops at a
%n stores used = 2, the number of characters consumed
text[2] is ‘a’, not NUL, so the whole text is rejected

Here is a reusable function built on that idea, with a table-driven test.

#include <stdio.h>

static int parse_int(const char *text, int *out)
{
    int value = 0;
    int used  = 0;

    if (sscanf(text, "%d%n", &value, &used) != 1)
        return 0;                 /* no number at the start */
    if (text[used] != '\0')
        return 0;                 /* something left after the number */

    *out = value;
    return 1;
}

int main(void)
{
    const char *samples[] = { "1348", "-7", "+9", "  42", "13a", "12 ", "", "abc" };
    const int count = (int)(sizeof samples / sizeof samples[0]);

    printf("%-10s %-6s %s\n", "input", "valid", "value");
    for (int i = 0; i < count; i++) {
        char shown[16];
        int  v = 0;

        snprintf(shown, sizeof shown, "\"%s\"", samples[i]);
        if (parse_int(samples[i], &v))
            printf("%-10s %-6s %d\n", shown, "yes", v);
        else
            printf("%-10s %-6s -\n", shown, "no");
    }
    return 0;
}

Build and run:

gcc -std=c17 -Wall -Wextra -o parse_int parse_int.c
./parse_int
input      valid  value
"1348"     yes    1348
"-7"       yes    -7
"+9"       yes    9
"  42"     yes    42
"13a"      no     -
"12 "      no     -
""         no     -
"abc"      no     -

Read the results carefully, because each one teaches something:

  • +9 and -7 are accepted because %d understands an optional sign.
  • ” 42″ is accepted because %d skips leading white space on its own.
  • 13a and “12 ” are rejected because text[used] is not the null terminator. The trailing space is rejected on purpose. If you want to tolerate it, advance a pointer past isspace characters before the final comparison.
  • The empty string and abc are rejected because sscanf does not return 1.

One catch: if the %d conversion fails, %n is never executed, so used keeps its starting value. That is why the function checks the return value before it looks at used.

Check Every Character Yourself

Another way to validate input in C is to scan the string character by character before converting it. The rule for a decimal integer is simple: an optional sign, then at least one digit, then nothing else. Writing that rule as code makes the intent obvious and removes any doubt about what sscanf will accept.

#include <ctype.h>
#include <stdio.h>

static int looks_like_integer(const char *s)
{
    size_t i = 0;

    if (s[i] == '+' || s[i] == '-')
        i++;
    if (s[i] == '\0')
        return 0;                       /* empty, or a sign with nothing after it */

    for (; s[i] != '\0'; i++)
        if (!isdigit((unsigned char)s[i]))
            return 0;                   /* first bad character decides */
    return 1;
}

int main(void)
{
    const char *inputs[] = { "1348", "-7", "+", "", "12.5", "4o4", "007" };
    const int count = (int)(sizeof inputs / sizeof inputs[0]);

    for (int i = 0; i < count; i++) {
        int v = 0;

        if (looks_like_integer(inputs[i]) && sscanf(inputs[i], "%d", &v) == 1)
            printf("\"%s\" -> accepted, value = %d\n", inputs[i], v);
        else
            printf("\"%s\" -> rejected\n", inputs[i]);
    }
    return 0;
}
"1348" -> accepted, value = 1348
"-7" -> accepted, value = -7
"+" -> rejected
"" -> rejected
"12.5" -> rejected
"4o4" -> rejected
"007" -> accepted, value = 7

Two details deserve attention. First, the cast to unsigned char before isdigit is required: the ctype functions take an int that must be either EOF or a value representable as unsigned char, and a negative char value is undefined behaviour. Second, 007 is accepted and converts to 7, because %d always reads base 10. A function such as strtol with base 0 would treat the same text as octal, so decide which behaviour you want.

Safer Conversion With strtol

sscanf has one weakness that neither of the previous techniques can fix: a number too large for the variable. The C standard makes that undefined behaviour. The strtol function converts to long, reports where it stopped through its second argument, and signals overflow by setting errno to ERANGE. Combined with a range check against INT_MIN and INT_MAX it gives a complete validator.

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

static int parse_int_strict(const char *text, int *out)
{
    char *end = NULL;

    errno = 0;
    long v = strtol(text, &end, 10);

    if (end == text)
        return 0;                          /* no digits at all */
    if (*end != '\0')
        return 0;                          /* trailing junk */
    if (errno == ERANGE || v < INT_MIN || v > INT_MAX)
        return 0;                          /* does not fit */

    *out = (int)v;
    return 1;
}

int main(void)
{
    const char *samples[] = {
        "2147483647", "2147483648", "99999999999999999999",
        "-2147483648", "12x", ""
    };
    const int count = (int)(sizeof samples / sizeof samples[0]);

    for (int i = 0; i < count; i++) {
        int v = 0;
        if (parse_int_strict(samples[i], &v))
            printf("%-22s accepted -> %d\n", samples[i], v);
        else
            printf("%-22s rejected\n", samples[i]);
    }
    return 0;
}
2147483647             accepted -> 2147483647
2147483648             rejected
99999999999999999999   rejected
-2147483648            accepted -> -2147483648
12x                    rejected
                       rejected

The three checks in order are: no digits consumed (endptr equals the start), characters left over (endptr does not point to the terminator), and value does not fit. Setting errno to zero before the call matters, because strtol never clears it for you.

TechniqueRejects trailing junkDetects overflowTypical cost
atoiNoNoSmallest, but cannot report any error
sscanf with %dNoNo (undefined)Heavy library code
sscanf with %d%nYesNo (undefined)Heavy library code
strtol with checksYesYesLight, preferred on small targets

On a 64-bit Linux machine long has 64 bits, so 2147483648 converts fine and is then rejected by the INT_MAX comparison. On a 32-bit microcontroller long has 32 bits and the same text sets ERANGE instead. Either way the function answers correctly, which is exactly why the double check is worth writing.

A Serial Command Parser That Validates Input in C

Now apply everything to a realistic problem. A device accepts two commands on its UART: GET, and SET followed by a level from 0 to 255. The parser must reject anything else without crashing or acting on half-understood text.

#include <stdio.h>
#include <string.h>

static void handle(const char *line)
{
    char cmd[8] = "";
    int  arg    = 0;
    int  used   = 0;
    int  n      = sscanf(line, "%7s %d%n", cmd, &arg, &used);

    if (n == 1 && strcmp(cmd, "GET") == 0) {
        printf("%-14s -> GET accepted\n", line);
    } else if (n == 2 && strcmp(cmd, "SET") == 0) {
        if (line[used] != '\0')
            printf("%-14s -> rejected: trailing text\n", line);
        else if (arg < 0 || arg > 255)
            printf("%-14s -> rejected: %d outside 0..255\n", line, arg);
        else
            printf("%-14s -> SET %d accepted\n", line, arg);
    } else {
        printf("%-14s -> rejected: bad format\n", line);
    }
}

int main(void)
{
    const char *lines[] = { "SET 120", "SET abc", "SET 9999", "GET", "SET 50 extra", "" };
    const int count = (int)(sizeof lines / sizeof lines[0]);

    for (int i = 0; i < count; i++)
        handle(lines[i]);
    return 0;
}
SET 120        -> SET 120 accepted
SET abc        -> rejected: bad format
SET 9999       -> rejected: 9999 outside 0..255
GET            -> GET accepted
SET 50 extra   -> rejected: trailing text
               -> rejected: bad format

Study how each rejection happens. SET abc yields a return value of 1 because only the word converted, so the second branch never matches. SET 9999 converts fine but fails the range test. SET 50 extra is caught by the %n position check. GET returns 1 as well, which is exactly why the code tests the command name together with the count. The empty line returns EOF, which falls into the final else.

Common Mistakes When You Validate Input in C

MistakeConsequenceFix
Trusting a return value of “not zero”Partial numbers pass as validCompare with the exact expected count
Using atoi on untrusted textReturns 0 for garbage, indistinguishable from a real 0Use strtol and check endptr
Forgetting errno = 0 before strtolStale ERANGE from an earlier callReset it every time
Validating once, using laterText changes between check and useConvert once, keep the typed value
Checking range only on one sideNegative numbers slip throughTest both minimum and maximum
Passing plain char to isdigitUndefined behaviour for negative valuesCast to unsigned char

Best Practices, Performance and Security

  • Validate at the boundary where data enters the program, then pass typed values inward.
  • Prefer an allow-list (“only digits”) to a block-list (“no letters”).
  • Limit line length first by reading with fgets into a fixed buffer, then validate the content.
  • Reject and report, do not guess. A command parser that “fixes” bad input will eventually fix it wrongly.
  • Treat every UART, Bluetooth, network and file input as hostile. Many real firmware vulnerabilities began as an unchecked length or number.
  • On tiny targets prefer strtol and hand-written scanners over the full scanf family to save flash and stack.
  • Validation costs a few comparisons per character, which is negligible next to the cost of acting on wrong data.

Summary and Key Takeaways

  • A plain sscanf %d accepts 13a as 13, so a return value of 1 alone is not validation.
  • %n records how many characters were consumed, letting you detect trailing text.
  • A manual scan with isdigit makes the accepted grammar explicit.
  • strtol with endptr, errno and range checks is the most complete and the lightest option.
  • Always check range after type, and reject rather than repair.

Conclusion

Learning to validate input in C is less about clever functions and more about a mindset: nothing that arrives as text is a number until you have proved it. The three techniques in this lecture cover almost every situation you will meet, from a student exercise to a production command interface. Practise them on your own examples, then move on to the next lecture, where we apply careful pointer logic to a classic string problem. Everything here belongs to our free C programming course, and the same material makes you stronger in the wider free embedded C course.

Frequently Asked Questions About Validating Input in C

How do I check if input is an integer in C?

Convert it with strtol and check that endptr moved, that endptr points to the null terminator, and that errno is not ERANGE. Alternatively use sscanf with %d%n and compare the consumed count with the string length.

What does %n do in sscanf?

It stores the number of characters consumed so far into an int you pass by address. It is not counted in the return value and is skipped entirely if an earlier conversion fails.

Why is atoi considered unsafe?

atoi returns 0 on failure, so you cannot tell bad input from a real zero, and it gives no overflow information.

Does sscanf detect integer overflow?

No. If the number does not fit the target object the behaviour is undefined. Use strtol and compare against INT_MIN and INT_MAX.

Why cast to unsigned char before calling isdigit?

The ctype functions require an argument that is EOF or representable as unsigned char. Passing a negative char value is undefined behaviour.

Is it enough to check that the return value is greater than zero?

No. Compare it with the exact number of conversions you expect, and also check for leftover text.

Should I validate input in firmware that only talks to my own PC tool?

Yes. Cables get noisy, tools get replaced, and attackers reach interfaces you thought were private. Validation is cheap insurance.

Continue the Free Embedded C Course

Safe input handling is the first skill every firmware engineer needs. Keep building it lecture by lecture.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →