一个tm结构中的错误破坏了其他tm结构
Error in one tm-structure corrupting other tm-structures
我偶然发现了这种行为,想知道这是否在预料之中(对我来说看起来不对)。
我强制在一个特定的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;
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 将 OLE 自动化日期 (OADate) 双精度转换为结构 tm,而不使用 VariantTime到SystemTime
- 复制结构 tm
- 无法声明指向"结构 TM& 的指针
- 如何在 C++ 中将结构 TM 转换为time_t
- C++结构TM&time_t
- 如何检测在使用tm结构时是否存在闰秒
- 如何判断我的结构tm是否处于无效状态
- 如何在不更改原始 tm 结构的情况下使用 mktime()
- C++ 将包含 UTC 日期和时间的字符串转换为 TM 结构
- 如何用自己的值填充tm结构,然后打印出来
- 为什么mktime()会更改我的tm结构的年份
- 为什么在调用 localtime() 函数之前不需要 malloc 结构 tm 指针?
- 正在查找具有tm以外的成员对象的另一个时间结构
- 我如何使用tm结构添加分钟到当前时间
- 一个tm结构中的错误破坏了其他tm结构
- 在c++中调用time会改变我的结构体tm
- 直接设置结构 tm 属性的值不起作用
- 当给定一个有效的结构tm时,Mktime返回-1