CERT.FIO.RESET
Reset strings after fgets() or fgetws() fails.
The CERT.FIO.RESET checker detects uses of a string after fgets() or fgetws() fails without resetting the string to a known value. A failed call can leave the destination array in an indeterminate state, and subsequent use can result in undefined behavior.
Vulnerability and risk
If fgets() or fgetws() fails, the contents of the destination array are indeterminate. Using the array before resetting it can produce incorrect results or undefined behavior.
Mitigation and prevention
Check the return value of fgets() or fgetws(). If the call fails and the string will be used later, reset the string to a known value before using it.
Vulnerable code example
#include <stdio.h>
void use(const char* value);
void read_value(FILE* file)
{
char buffer[1024];
if (fgets(buffer, sizeof(buffer), file) == NULL) {
/* Handle the error and continue. */
}
use(buffer);
}
The failed call can leave buffer in an indeterminate state before it is passed to use().
Fixed code example
#include <stdio.h>
void use(const char* value);
void read_value(FILE* file)
{
char buffer[1024];
if (fgets(buffer, sizeof(buffer), file) == NULL) {
/* Handle the error and continue. */
buffer[0] = '\0';
}
use(buffer);
}
The fixed example resets buffer before using it after a failed call. For fgetws(), reset the destination to an empty wide string.