Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The gets() function, which was deprecated in the C99 Technical Corrigendum 3 and removed from C11, is inherently unsafe and should never be used because it provides no way to control how much data is read into a buffer from stdin. This noncompliant code example assumes that gets() will not read more than BUFSIZ BUFFER_SIZE - 1 characters from stdin. This is an invalid assumption, and the resulting operation can cause a buffer overflow. Note further that BUFSIZ is a macro integer constant, defined in stdio.h, representing a suggested argument to setvbuf() and not the maximum size of such an input buffer.

The gets() function reads characters from the stdin into a destination array until end-of-file is encountered or a newline character is read. Any newline character is discarded, and a null character is written immediately after the last character read into the array.

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>
#define BUFFER_SIZE 1024
 
void func(void) {
  char buf[BUFSIZBUFFER_SIZE];
  if (gets(buf) == NULL) {
    /* Handle error */
  }
}

...

After the loop ends, if feof(stdin) != 0, the loop has read through to the end of the file without encountering a newline character. Similarly, if ferror(stdin) != 0, a read error occurred before the loop encountered a newline character, and if chars_read > index, the input string has been truncated. FIO34-C. Do not compare Distinguish between characters read from a file with and EOF or WEOF is also applied in this solution.

...

CERT C Secure Coding Standard

STR03-C. Do not inadvertently truncate a string
STR07-C. Use the bounds-checking interfaces for remediation of existing string manipulation code
MSC24-C. Do not use deprecated or obsolescent functions
MEM00-C. Allocate and free memory in the same module, at the same level of abstraction
FIO34-C. Do not compare Distinguish between characters read from a file with and EOF or WEOF

CERT C++ Secure Coding StandardSTR31-CPP. Guarantee that storage for character arrays has sufficient space for character data and the null terminator
ISO/IEC TR 24772:2013String Termination [CJM]
Buffer Boundary Violation (Buffer Overflow) [HCB]
Unchecked Array Copying [XYW]
ISO/IEC TS 17961

Using a tainted value to write to an object using a formatted input or output function [taintformatio]
Tainted strings are passed to a string copying function [taintstrcpy]

MITRE CWECWE-119, Failure to constrain operations within the bounds of an allocated memory buffer
CWE-120, Buffer copy without checking size of input ("classic buffer overflow")
CWE-193, Off-by-one error

...