使用gmtime和mktime在同一天制作两个time_t值,“功能可能不安全”错误

时间:2018-07-13 09:35:35

标签: c++ visual-studio error-handling mktime time-t

我试图使用过去的time_t和新的时间,并使用gmtime,使它们都成为一个结构,我可以将新时间更改为一周的同一天,之后我希望新的更改时间回到time_t并返回。

因此,我的问题是,作为一名新程序员,我想知道下面的代码是否是正确的解决方法,如果可以,为什么我得到一个:

“”错误3错误C4996:'gmtime':此函数或变量可能不安全。考虑改用gmtime_s。要禁用弃用,请使用_CRT_SECURE_NO_WARNINGS。有关详细信息,请参见在线帮助。”错误?

代码:

    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;
}

1 个答案:

答案 0 :(得分:1)

来自gmtime documentation

  

返回值指向静态分配的结构,该结构可能会被随后对任何日期和时间函数的后续调用所覆盖。

好的,这是linux文档,但是在Windows上的行为是相同的。

您正遇到以下问题:

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

thennow都指向同一个对象!因此,您从第一次通话gmtime中丢失了信息,该信息被第二次通话覆盖!

MSVC尝试通过默认情况下不允许使用gmtime来避免此类错误。要关闭警告/错误,您需要使用错误中显示的宏:_CRT_SECURE_NO_WARNINGS。在包含标题之前,先在开头定义#define,或者在IDE的项目设置中将其添加为预处理程序定义。

旁注:正确解决您的错误:

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