Introduction / Context:
Reading entire lines including spaces is a common need in C. Historically, gets was used, but it became notorious for buffer overflow vulnerabilities and has been removed from the C standard. Knowing the safe alternative is essential for writing robust, secure C programs.
Given Data / Assumptions:
- We need to read a whole line that may contain spaces.
- We want a function that prevents buffer overflows by respecting buffer size.
- Portable, standard C behavior is desired.
Concept / Approach:
- fgets(buffer, size, stream) reads at most size-1 characters and always terminates with a null byte if any characters are read, preventing overflows.
- gets reads until newline with no size limit; it cannot prevent writing past the end of the buffer.
- Some libraries offer getline or gets_s, but these are not universally portable in the same way as fgets.
Step-by-Step Solution:
Specify the buffer and its size → call fgets(buf, sizeof buf, stdin).On success, fgets stores the line including the trailing newline (unless the line exceeded the buffer or EOF occurred).Thus, the safe choice is fgets because it respects buffer boundaries.
Verification / Alternative check:
Security guidelines and modern compilers warn against gets; many toolchains remove it entirely. Compiling code using gets often fails.
Why Other Options Are Wrong:
- gets(): Dangerous and removed from the standard; it cannot limit input length.
- getline(): Useful but POSIX, not ISO C; availability varies.
- gets_s(): Bounds-checked but not portable across all environments; not ISO C90/C99.
Common Pitfalls:
- Forgetting that fgets keeps the trailing newline; trim it if needed.
- Passing the wrong size to fgets (must be the buffer's capacity).
Final Answer:
fgets()
Discussion & Comments