Daniel Peedah
Daniel Peedah

Reputation: 171

Making two time_t values the same day using gmtime and mktime, 'function may be unsafe' error

I am trying to use a time_t from the past, and a new time, and using gmtime, make them both a structure to which I can change the new time to the same day of the week, after this I wish to make the new changed time back into a time_t and return it.

So my issues are, as a new programmer, I wish to know if the below code the right way to go about it, and if so, why do I get a:

""Error 3 error C4996: 'gmtime': This function or variable may be unsafe. Consider using gmtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details." Error?

Code:

    time_t copyStartTime(time_t &startTime,time_t eventTime ) //finds exact time of startTime and returns it
{
    cout << eventTime << "\n";
    cout << startTime << "\n";
    cin.get();
    tm* then = gmtime(&startTime);
    cout << (then->tm_hour);
    tm* now = gmtime(&eventTime);
    cout << (now->tm_hour);
    cin.get();
    then->tm_hour = now->tm_hour;
    time_t newTime = _mkgmtime(then);
    cout << newTime << "\n";
    cin.get();
    return newTime;
}

Upvotes: 0

Views: 287

Answers (1)

Aconcagua
Aconcagua

Reputation: 25516

From gmtime documentation:

The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

OK, this was linux documentation, but the behaviour is the same on windows.

And you are running into exactly the problem with:

tm* then = gmtime(&startTime);
cout << (then->tm_hour);
tm* now = gmtime(&eventTime);

then and now both point to the same object! So you lose the information from first call go gmtime, which is overwritten by second call!

MSVC tries to save you from this kind of error by just not allowing usage of gmtime by default. To switch the warning/error off, you need to use the macro that is shown in the error: _CRT_SECURE_NO_WARNINGS. Either #define it right at the start before including the header or add it as pre-processor definition in IDE's project settings.

Side note: Correctly resolving your bug:

tm then = *gmtime(&startTime);
tm now = *gmtime(&eventTime);

Upvotes: 1

Related Questions