2016-10-28 24 views
0

私はこの現象に遭遇し、これが期待されているかどうかを知りたいと思います。あるtm構造のエラーが他のtm構造を破損しています

ある特定のtm構造でエラーが発生し、他のすべてが破損します。

これは、(問題を再現するminimunにストリップダウン)コード

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)で未処理の例外:無効なパラメータでした無効なパラメータを致命的とみなす関数に渡されます。

答えて

3

そう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; 
+0

'のstd :: put_time'は' time_point'なく 'TM *' – Mgetz

+0

を取ると、nullptrリターンをチェックし、既存のlocaltime_rまたはlocaltime_sの選択肢を検討すべき理由です。 –

+0

OOok!ありがとう@KennyOstrom。更新されます。 – user4581301

関連する問題