Coding/Learn/c/c user input and io
C Foundational Course
01.Introduction, Compilation Pipeline & Syntax
02.Variables, Primitives & Explicit Type Casting
03.Operators, Precedence & Booleans (<stdbool.h>)
04.Control Flow: If-Else, Ternary & Switch
05.Loops (For, While, Do-While) & Jump Statements
06.Contiguous Arrays & Multi-Dimensional Matrices
07.Null-Terminated Strings & <string.h>
08.User Input, scanf & fgets Buffer Safety
09.Pointers, Memory Addresses & Dereferencing
10.Functions, Prototypes & Pass-by-Pointer
11.11. Recursion & High-Speed Function Pointers
12.File Streams: Create, Write & Read (fopen/fclose)
13.Structures, Unions & typedef Aliasing
14.Memory Word Alignment & Struct Padding
15.Enums & Bitwise Manipulation (Flags & Masks)
16.Dynamic Memory: malloc, calloc, realloc & free
17.Defensive Error Handling, errno & Assertions
18.Preprocessor Macros & Storage Classes
19.Fixed-Width Types (stdint.h), Math & Time (<time.h>)
20.Capstone: High-Performance In-Memory Key-Value Engine
Course Certificate0%

Complete all lessons to earn

LearnUser Input, scanf & fgets Buffer Safety
8 / 20 0%
Lesson 08 of 20
6 mins read

User Input, scanf & fgets Buffer Safety

PreviousNext Lesson
In Plain English

While scanf("%d", &val) reads numeric primitives via address pointers, reading strings with unbounded scanf("%s") causes severe buffer overflow exploits. Modern production C uses fgets(buf, size, stdin) and strcspn() to sanitize line breaks safely.

The Mental Model

"Unbounded scanf is leaving an open funnel where a user can pour 10 gallons of water into a 1-pint glass; fgets is a smart measuring valve that cuts off flow before spilling."

Deep Dive: How It Works

Address Operator (&): scanf requires memory addresses of destination variables.

fgets Safety: Enforces a maximum character read limit, automatically appending \0.

Newline Sanitization: strcspn(buf, "\r\n") finds the trailing newline to replace it with \0.

Syntax Blueprint

if (fgets(buf, sizeof(buf), stdin)) {
    buf[strcspn(buf, "\r\n")] = '\0';
}

Safely read bounded input line and strip trailing newline character.

PointCore Rules to Remember

Point star
fgets Over scanf: Always prefer fgets over gets (which is removed from C11) or raw scanf for strings.
Point star
Buffer Bounds: Pass sizeof(buffer) to guarantee no memory corruption.
Point star
Newline Trimming: strcspn instantly finds newlines from Enter key presses.

Common Beginner Traps & How to Fix Them

Mistake:Using gets() in legacy codebases.

Why it happens: gets() cannot check buffer bounds and was completely removed from the ISO C11 standard for security.

How to fix: Replace all instances of gets(buf) with fgets(buf, sizeof(buf), stdin).

Pro Tip: Always check the return value of fgets (NULL on EOF or error) before processing input buffers.

Live Interactive Example

Hit Run Code to see it live
Sanitize Input Buffer
C11 / GCC 9.2
1
2
3
4
5
6
7
8
9
10
Output Console
Click "Run Code" to view the rendered output.
How it works: strcspn finds the index of \n and overwrites it with \0.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Inspect Sanitized Buffer Length

  • PointPrint the length of the sanitized buffer using strlen: "Length: %zu\n".
1
2
3
4
5
6
7
8
9
10
11
12
13
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates