scanf string input without a field width

scanf string input without a field width

Description

Without a field width, a %s or scanset conversion in the scanf family can read more input than the destination buffer can hold.

Potential impact

  • Stack buffer overflows, crashes, or code execution may result.

Remediation

Specify a field width smaller than the destination buffer, or use fgets.

Examples

Before

c
char name[16];
scanf("%s", name);

After

c
char name[16];
scanf("%15s", name);

Explanation:

  • Before: %s has no input-width limit.
  • After: The maximum width is 15 characters for a 16-byte buffer, leaving room for the terminating null character.

References