
Error Status Misinterpreted
First, let’s see how the developer wrote the function that accepts a month’s abbreviated name and returns its number.
static const char qt_shortMonthNames[][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static int fromShortMonthName(QStringView monthName)
{
for (unsigned int i = 0;
i < sizeof(qt_shortMonthNames) / sizeof(qt_shortMonthNames[0]); ++i)
{
if (monthName == QLatin1String(qt_shortMonthNames[i], 3))
return i + 1;
}
return -1;
}
If successful, the function returns the month number (a value from 1 to 12). If the month’s name is incorrect, the function returns a negative value (-1). Note that the function cannot return 0.
However, the function above is used where the developer expects it to return null in case of an error. Here is the code fragment that uses the fromShortMonthName function incorrectly:
QDateTime QDateTime::fromString(QStringView string, Qt::DateFormat format)
{
....
month = fromShortMonthName(parts.at(1));
if (month)
day = parts.at(2).toInt(&ok);
// If failed, try day then month
if (!ok || !month || !day) {
month = fromShortMonthName(parts.at(2));
if (month) {
QStringView dayPart = parts.at(1);
if (dayPart.endsWith(u'.'))
day = dayPart.chopped(1).toInt(&ok);
}
}
....
}
The program never reaches the code that checks the month number for null, and continues to run with an incorrect negative month number. The PVS-Studio analyzer sees a whole bunch of inconsistencies here and reports them with four warnings at once:
- V547 [CWE-571] Expression ‘month’ is always true. qdatetime.cpp 4907
- V560 [CWE-570] A part of conditional expression is always false: !month. qdatetime.cpp 4911
- V547 [CWE-571] Expression ‘month’ is always true. qdatetime.cpp 4913
- V560 [CWE-570] A part of conditional expression is always false: !month. qdatetime.cpp 4921
Please click here to see more bugs from this project.