Reputation: 194
I have an issue with the following fuction:
std::string TimeToTimestampStr(time_t t)
{
tm aTm;
ACE_OS::localtime_r(&t, &aTm);
// YYYY year
// MM month (2 digits 01-12)
// DD day (2 digits 01-31)
// HH hour (2 digits 00-23)
// MM minutes (2 digits 00-59)
// SS seconds (2 digits 00-59)
char buf[20];
snprintf(buf, 20, "%04d-%02d-%02d_%02d-%02d-%02d",
(aTm.tm_year+1900)%10000,
(aTm.tm_mon+1)%13,
aTm.tm_mday%32,
aTm.tm_hour%24,
aTm.tm_min%60, // warning on this parameter
aTm.tm_sec%60);
return std::string(buf);
}
error: ‘%02d’ directive output may be truncated writing between 2 and 3 bytes into a region of size between 2 and 6 [-Werror=format-truncation=]
Not sure why this is an issue, 2-3 bytes should not be truncated in a region of size 2-6 bytes, so what is the reason for the warning? Best guess is that 3 bytes could be truncated by the lower limit of the region (2)? But that's complete bogus - region is of size up to 6 bytes, and should only truncate if more than 6 bytes are being written.... right?
EDIT: other questions I found were related to writing more bytes to a region of less bytes, which led be to adding % to enforce the upper size limit of input.
Upvotes: 2
Views: 2915
Reputation: 32586
in tm
the fields are int
so there are signed, for the compiler all the numbers you compute can be negative, but you sized your array supposing there are all positive because you know what localtime_r
does, but for the compiler 26 bytes are necessary because the worst case is like -9999--13--31_-23--59--59
Of course having the size 20 there is no undefined behavior because you use snprintf
rather than printf
, but for instance compiling with -Wall
activate the production of the warning
Replace the size 20 by at least 26 and you will not have the warning
Upvotes: 2