kdg1955
kdg1955

Reputation: 325

mktime : unexpected result

I want to convert a struct tm to a time_t with mktime in c.
Here is my code:

#include <stdio.h>
#include <time.h>

int main(int argc, char **argv)
{
struct tm _tm;
time_t _t;

  strptime ("20160220", "%Y%m%d", &_tm);
  printf ("1: struct tm => %04d%02d%02d\n", _tm.tm_year+1900
                                          , _tm.tm_mon+1
                                          , _tm.tm_mday);

  _t = mktime(&_tm);
  printf ("2: struct tm => %04d%02d%02d | time_t: %lu\n"
                                                  , _tm.tm_year+1900
                                                  , _tm.tm_mon+1
                                                  , _tm.tm_mday
                                                  , _t);

  _tm = *(localtime(&_t));
  printf ("3: struct tm => %04d%02d%02d | time_t: %lu\n"
                                                  , _tm.tm_year+1900
                                                  , _tm.tm_mon+1
                                                  , _tm.tm_mday
                                                  , _t);
  return 0;
}

But it give me an unexpected output:

1: struct tm => 20160220
2: struct tm => 24941121 | time_t: 16563985201
3: struct tm => 24941121 | time_t: 16563985201

Apparently the value of _tm changes in mktime, and it returns an incorrect value.
What I'm doing wrong? I compile it (64bit) on a linux system with gcc version 4.9.2

Upvotes: 3

Views: 411

Answers (1)

2501
2501

Reputation: 25753

You have undefined behavior because the _tm isn't correctly initialized.

Function strptime will only set the members specified in the format string, others will be left unmodified, thus their values will be indeterminate.

Then the function mktime will fix the values that are not in the range thus giving you a vastly different time, because of uninitialized member values in _tm.

The solution is to initialize correctly:

struct tm _tm = { 0 };

(And don't use prefix _ in names, as it is reserved by C)

Upvotes: 2

Related Questions