2

現在の日付と時刻を出力する必要がある単純なログ機能があります。を返す関数内で実行していますchar *char *これをに設定しようとするとfprintf()、文字列がファイルに出力されません。なぜですか?

日時を構成する関数は次のとおりです。

char * UT::CurrentDateTime()
{
     char buffer [50];
     time_t t = time(0);   // get time now
     struct tm * now = localtime( & t ); 
     int n=sprintf(buffer, "%d:%d:%d %d:%d:%d:", (now->tm_year + 1900),
                   (now->tm_mon + 1), now->tm_mday, now->tm_hour, now->tm_min,
                   now->tm_sec);
     return buffer;
}

ログは次のとおりです。

const char *time =__TIME__; // compilation time 
char *currentTime = UT::CurrentDateTime(); // it's a static method; also tried to set it to const
fprintf(fp, "%s %s %s %s %s %d %s\n", __TIME__, pType, __DATE__,
        currentTime, pFileName, lineNo, pMsg.c_str());
fflush(fp);

日付/時刻を除いてすべてが印刷されchar *ます。なんで?

4

1 に答える 1

5
char * UT::CurrentDateTime()
{
     char buffer [50];
     /* ... */
     return buffer;
}

すぐに停止するメモリバッファへのポインタを返しました。から返されたポインタを使用する関数はすべて、ガベージCurrentDateTime()に依存しています。

あなたのコンパイラはこれについてあなたに警告するべきでした。自分の危険でコンパイラの警告を無視してください。

代わりに、これを介して割り当てるか、char *buffer = malloc(50 * sizeof char);C ++のメモリ割り当てメカニズムを使用して、関数が「ライブ」で実行されている時間よりも長く存続できるメモリを割り当てます。

于 2011-12-29T06:05:16.830 に答える