我偶然发现了这种行为,并想知道这是否是意料之中的(在我看来不对)。
我强制错误在一个特定的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 (MyTest.exe)异常:一个无效的参数被传递给一个认为无效参数是致命的函数。
发布于 2016-10-28 18:44:51
引用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);如果你要在任何一段时间内保持它的话,就制作一份可以工作的副本。
肯尼·奥斯特罗姆在评论中提出了一个很好的观点。我没有处理空返回的情况和复制空..。不是个好主意。
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;https://stackoverflow.com/questions/40311247
复制相似问题