...
If at the end of the loop feof(stdin) != 0, the loop has read through to the end of the file without encountering a new-line character. If at the end of the loop ferror(stdin) != 0, a read error occurred before the loop encountered a new-line character. If at the end of the loop chars_read > index, the input string has been truncated. Rule VOID FIO34-CPP. Use int to capture the return value of character IO functions is also applied in this solution.
...
The following test for the while loop is normally sufficient.
| Code Block |
|---|
while ( ( (ch = getchar()) != '\n') && ch != EOF ) {
|
See VOID FIO35-CPP. Use feof() and ferror() to detect end-of-file and file errors when sizeof(int) == sizeof(char) for the case where feof() and ferror() must be used instead.
...
According to TR 24731 [ISO/IEC TR 24731-2006]:
No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.
If end-of-file is encountered and no characters have been read into the destination array, or if a read error occurs during the operation, then the first character in the destination array is set to the null character and the other elements of the array take unspecified values.
| Code Block | ||||
|---|---|---|---|---|
| ||||
char buf[BUFFERSIZE];
if (gets_s(buf, sizeof(buf)) == NULL) {
/* handle error */
}
|
Noncompliant Code Example ( scanf() )
...
Klocwork Version 8.0.4.16 can detect violations of this rule with the NNTS.TAINTED, SV.STRBO.GETS, and SV.USAGERULES.UNBOUNDED_STRING_COPY checkers.
The Coverity Prevent Version 5.0 Coverity Code Advisor version 7.5 can detect violations of this rule. The OVERRUN_STATIC, and OVERRUN_DYNAMIC checker checkers can detect the instances of out of bound read/write to a static or dynamically allocated array.
...
[Drepper 06] Section 2.1.1, "Respecting Memory Bounds"
[ISO/IEC 14882-2003] Sections 3.6.1 Main function, and 18.7 Other runtime support
[ISO/IEC 9899:1999] Section 7.19, "Input/output <stdio.h>"
[ISO/IEC TR 24731-2006] Section 6.5.4.1, "The gets_s function"
[Lai 06]
[MITRE 07] CWE ID 120, "Unbounded Transfer ('Classic Buffer Overflow')"
[NIST 06] SAMATE Reference Dataset Test Case ID 000-000-088
[Seacord 05a] Chapter 2, "Strings"
...
STR34-CPP. Cast characters to unsigned types before converting to larger integer sizes 07. Characters and Strings (STR) STR36STR08-CPP. Do not specify the bound of a character array initialized with a string literal