I understand snprintf should not result in buffer overflow. But still why does the tool raise this complaint?
Often I have seen analysis tool's complaints are pedantically real, yet the tool points to the wrong original culprit.
Code has at least this weakness
Potential junk in timebuf[]
char timebuf[20];
// Enough space?
strftime(timebuf, sizeof(timebuf),"%Y-%m-%d %H:%M:%S", adjustedtime);
As adjustedtime->tm_year
, an int
, may have values in the range -2147483648 ... 2147483647
, more than size 20 needed.
Avoid under sizing. Recommend:
#define INT_TEXT_LENGTH_MAX 11
char timebuf[6*INT_TEXT_LENGTH_MAX + sizeof "%Y-%m-%d %H:%M:%S"];
Further, it the buffer is not big enough, then:
If the total number of resulting characters including the terminating null character is not more than maxsize, the strftime
function returns the number of characters placed into the array pointed to by s not including the terminating null character. Otherwise, zero is returned and the contents of
the array are indeterminate. C17dr § 7.27.3.5 Library 8
Thus an analysis tool can assume any content for timebuf[]
including a non-string following an unchecked strftime()
. That can easily break snprintf(gendata, sizeof(gendata), "%s", timebuf);
as "%s"
requires a string, which timebuf[]
is not guarantied to be. The sizeof(gendata)
in snprintf(gendata, sizeof(gendata), ...
is not sufficient to prevent UB of an unterminated timebuf[]
.
Better code would also check the size.
struct tm *adjustedtime = localtime(&t);
if (adjustedtime == NULL) {
Handle_Error();
}
if (strftime(timebuf, sizeof(timebuf),"%Y-%m-%d %H:%M:%S", adjustedtime) == 0) {
Handle_Error();
}
Now we can continue with snprintf()
code.