What does mktime overflow with the parameter?
Pergunta
According to standard, mktime
should perform normalisation - when you want to add a minute and a half to struct tm
, you add 90 seconds to tm_sec
and call mktime
, ignoring its return value.
What I didn't find in the standard is if the parameter is normalised even if it cannot be represented in time_t
(for example having the year set to 2100).
So, is this code safe?
struct tm future;
memset(&future, 0, sizeof(future));
future.tm_mon = 1;
future.tm_sec = 90; //I want this to be normalised by mktime
future.tm_year = 200; //but this can cause troubles
mktime(&future);
//future.tm_sec should be 30
//future.tm_min should be 1
//future.tm_year should be still 200
Solução
The C standard has this to say about mktime()
:
On successful completion, the values of the
tm_wday
andtm_yday
components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value oftm_mday
is not set untiltm_mon
andtm_year
are determined.
So you can only rely on the normalisation being performed if the function completed successfully.
Outras dicas
You need to check the return value of mktime
. You should not ignore the return value from library functions! (exception for printf
and a (not so) few others).
If it returns (time_t)-1
the result is not trustworthy.
See an example at http://codepad.org/KTZwUHt0
The same code on my computer prints
time_t is 64 bits long normalized to 2100-01-31 T 00:01:30