Search code examples
cwindowstmlocaltime

localtime() returns a pointer to a structure with uninitialized members


char datetime[DATETIME_LEN];
time_t timer;
struct tm* tm_info;

timer = time(NULL);
tm_info = localtime(&timer); // debug: tm_info: 0xcccccccccccccccc {tm_sec=??? tm_min=??? tm_hour=??? ...}
if (NULL == tm_info) // debug: 0xffffffffba9b07b0 {tm_sec=??? tm_min=??? tm_hour=??? ...}
{
  return;
}

strftime(datetime, DATETIME_LEN, "%Y%m%d_%H%M%S", tm_info); // Crush is here

At place where tm_info is used, tm_info's content is

tm_info's content

Any ideas about why unable to read memory? Does anyone had the same issue? By the way, if I use online compiler, I have no this issue.


Solution

  • As always, never blame the tool for failure. The function you are asking about has been in use by trillions of software programs since the late 1960s without problem, and today literally runs the world.

    The documentation makes it clear that the result is stored in static storage not controlled by you.

    There are two ways to handle this. The first is simply to copy the data out before anything can happen to it.

    struct tm tm_info = {0};
    struct tm * tm_info_p = localtime(&timer);
    if (tm_info_p) tm_info = *tm_info_p;
    

    That gets you your own local copy of the data.

    The other way is to use localtime_s() or localtime_r().

    #define __STDC_WANT_LIB_EXT1__ 1
    #include <time.h>
    
    struct tm tm_info;
    localtime_s(&timer, &tm_info);
    

    C is a fickle beast, and is not very forgiving when you make an error. Sorry.

    [edit] Yep, even experienced programmers make dumb mistakes... Thanks chux.