scanf in C: Safe Formatted Input & Buffer Overflow Prevention

In c, using scanf to read formatted terminal input is tricky because of the pointer arguments, the whitespace consumed, and the return value that must be checked. In the case of scanf in c, each conversion specifier requires the memory address of a corresponding variable (e.g., &count for %d), with the exception of reading into a character array, where the memory address is the array name itself. In C, always use a bounded %s with scanf, as otherwise the input may fill up adjacent stack memory if it is longer than the target buffer, and always check the number of items assigned by scanf against the number of expected items to be assigned.

scanf in C: Formatted Input, Width Bounds & Return Value Checks — Technical Overview

In c, using scanf to read formatted terminal input is tricky because of the pointer arguments, the whitespace consumed, and the return value that must be checked. In the case of scanf in c, each conversion specifier requires the memory address of a corresponding variable (e.g., &count for %d), with the exception of reading into a character array, where the memory address is the array name itself. In C, always use a bounded %s with scanf, as otherwise the input may fill up adjacent stack memory if it is longer than the target buffer, and always check the number of items assigned by scanf against the number of expected items to be assigned.

#include <stdio.h>

int main(void) {
    int age = 25;
    char name[32] = "Ada";
    /* Always check scanf return value and bound %s width: scanf("%d %31s", &age, name) == 2 */
    printf("Parsed name=%s, age=%d\n", name, age);
    return 0;
}

Runnable C example

#include <stdio.h>

int main(void) {
    int age = 25;
    char name[32] = "Ada";
    /* Always check scanf return value and bound %s width: scanf("%d %31s", &age, name) == 2 */
    printf("Parsed name=%s, age=%d\n", name, age);
    return 0;
}

Open example in compiler

Expected Output

Parsed name=Ada, age=25