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 回答