一个tm结构中的错误破坏了其他tm结构

Error in one tm-structure corrupting other tm-structures

本文关键字:tm 结构 坏了 其他 一个 错误      更新时间:2023-10-16

我偶然发现了这种行为,想知道这是否在预料之中(对我来说看起来不对)。

我强制在一个特定的tm结构中出现错误,并且所有其他的都被损坏。

这是代码(简化到最小值以重现问题)

int main()
{
    cout << "-----   Bug test - tm struc   -----" << endl;
    //--------------------------------------------
    //--- Setup struct tm ---
    time_t timet_Now = time(NULL);
    struct tm* tm1 = localtime(&timet_Now);
    struct tm* tm2 = localtime(&timet_Now);
    //--- Verify OK  -  cout shows "28/10/2016"---
    cout << tm1->tm_mday << " " << tm1->tm_mon << " " << tm1->tm_year << endl;
    cout << tm2->tm_mday << " " << tm2->tm_mon << " " << tm2->tm_year << endl;
    // ... so far, so good 
    // --- Force an error in a different tm struct (xxtm)
    time_t xtimet = 1464778020000;
    struct tm* xxtm = localtime(&xtimet);  //<<< xxtm = null - no runtime error
    //--- tm1 and tm2 are now corrupted - cout shows "-1/-1/-1"
    cout << tm1->tm_mday << " " << tm1->tm_mon << " " << tm1->tm_year << endl;
    cout << tm2->tm_mday << " " << tm2->tm_mon << " " << tm2->tm_year << endl;
    //--- This next line crashes the application, as tm1 is corrupted
    char* c = asctime(tm1);
    return 0;
}

崩溃错误是: MyTest.exe中0x0FA520B5 (ucrtbased.dll)的未处理异常:将无效参数传递给认为无效参数致命的函数。

引用http://en.cppreference.com/w/cpp/chrono/c/localtime

成功时

指针指向静态内部std::tm对象,否则为NULL。该结构可以在std::gmtime、std::localtime和std::ctime之间共享,并且可以在每次调用时重写。

换句话说,所有的struct tm *最终都指向相同的位置。你可能想要

struct tm tm1 = *localtime(&timet_Now);

,如果你要保存它一段时间,就做一份副本。

Kenny Ostrom在评论中提出了一个很好的观点。我没有处理NULL返回情况和复制NULL…不是个好主意。

struct tm * temp = localtime(&timet_Now);
if (temp == nullptr)
{
    // handle error. Throw exception, return, whatever, just don't run the next line 
}
struct tm tm1 = *temp;