localtime vs localtime_s and appropriate input arguments

C++Localtime

C++ Problem Overview


time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );

This returns: warning C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead.

time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime_s ( &rawtime );

When I change localtime to localtime_s I get: error C2660: 'localtime_s' : function does not take 1 arguments

Here is what I think is going on in the first block of code:

  • create an empty time_t variable.
  • create a pointer to timeinfo which is defined in ctime
  • write the rawtime into a rawtime reference
  • convert the rawtime into something meaningful to pedestrians
  1. Am I right?

  2. What second input parameter does localtime_s need?

  3. What's the worst that could happen if I just ignore the whole localtime safety issue.

C++ Solutions


Solution 1 - C++

localtime returns a pointer to a statically allocated struct tm.

With localtime_s, you pass in a pointer to a struct tm, and localtime_s writes its result data into that, so your code would change from:

struct tm *timeinfo;
timeinfo = localtime(&rawtime);

to something like:

struct tm timeinfo;
localtime_s(&timeinfo, &rawtime);

This way, it's writing to your buffer instead of having a buffer of its own.

Solution 2 - C++

localtime_s is just a microsoft implementation of the localtime functon, you can safely keep using locatime becaue it's C++ ISO compliant and ony microsoft marked it as "deprecated". The localtime function itself isn't deprecated at all in the C++ world.

The localtime_s reference says that these parameters should be passed to it:

_tm 
Pointer to the time structure to be filled in.
 time 
Pointer to the stored time.

Solution 3 - C++

As Lightness Races in Orbit pointed out, localtime is not thread safe as well as several other time function. I wanted to know more about the subject and I found a relevant blog post with a thoughrough explanation about that.

The quote below explains why localtimeis not thread-safe:

> [...] localtime returns a pointer to a static buffer (std::tm*). Another thread can call the function and the static buffer could be overwritten before the first thread has finished reading the content of the struct std::tm*.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProGirlXOXOView Question on Stackoverflow
Solution 1 - C++Jerry CoffinView Answer on Stackoverflow
Solution 2 - C++user1182183View Answer on Stackoverflow
Solution 3 - C++ForceMagicView Answer on Stackoverflow