fgetws() functions are typically used to read a newline-terminated line of input from a stream. Both functions read at most one less than the number of narrow or wide characters specified by an argument
n from a stream to a string. Truncation errors can occur if
n - 1 is less than the number of characters appearing in the input string prior to the new-line narrow or wide character (which is retained) or after end-of-file. This can result in the accidental truncation of user input.
Noncompliant Code Example
This noncompliant code example copies the input string into a buffer, and assumes it captured all of the user's input.
However, if the last character in
buf is not a newline and the stream is not at the end-of-file marker, the buffer was too small to contain all of the data from the user. For example, because the buffer is only 8 characters in length, if the user input
"Hello World\n", the buffer would contain
"Hello W" terminated by a null character.
Compliant Solution (Fail on Truncation)
This compliant solution examines the end-of-file marker for the stream and the last character in the buffer to determine whether it is a newline or not. If it is the end of file, or the last character is a newline, then the buffer contains all of the user's input. However, if the last character is not at the end-of-file and not a newline then the user's input has been truncated.
Compliant Solution (Expanding Buffer)
This compliant solution solves the problem by expanding the buffer to read the entire contents from
stdin instead of failing if the caller did not allocate enough space. If the allocation fails, it will return
NULL, but otherwise, it returns a buffer of the received data, which the caller must free.
Compliant Solution (POSIX
getline() function was originally a GNU extension, but is now standard in POSIX.1-2008. It also fills a string with characters from an input stream. In this case, the program passes it a NULL pointer for a string, indicating that
getline() should allocate sufficient space for the string and the caller frees it later.
Incorrectly assuming a newline character is read by
fgetws() can result in data truncation.
|LDRA tool suite||9.7.1||44 S||Enhanced enforcement|