我有以下代码
void _log_message(const char* fmt, ...)
{
va_list arg;
ofstream logfile;
cout << "Open Log File" << endl;
logfile.open(LOG_FILE, ios::out | ios::app);
if(!logfile.is_open()) return;
time_t t = time(NULL);
struct tm *tmptr = gmtime(&t);
char tmStr[70];
if (tmptr == NULL || strftime(tmStr, sizeof tmStr, "%Y-%m-%d %H:%M:%S", tmptr) == 0)
{
boost::format errFormat("gmtime() failed in file %s at line # %d\n");
logfile << errFormat % __FILE__ % (int)(__LINE__-3) << endl;
}
char* fmtMessage;
va_start(arg, fmt);
vsprintf(fmtMessage, fmt, arg);
va_end(arg);
try
{
cout << "write to logfile\t" << tmStr << "\t" << fmtMessage << endl;
logfile << tmStr << "\t" << fmtMessage << endl;
cout << "close logfile" << endl;
logfile.close();
cout << "close done" << endl;
}
catch(exception e)
{
cout << "Exception: " << e.what() << endl;
}
cout << "exit" << endl;
}它一直运行得很好,直到输出到日志文件。然后它就会停下来。没有我能发现的错误,也没有异常被捕获。
Open Log File
write to logfile 2014-07-30 16:12:34 Starting...我检查ps,发现进程是死的,而不是挂起的。
如果我从行尾删除endl,那么它可以工作,但在close方法调用中,它再次遇到同样的问题:
Open Log File
write to logfile 2014-07-30 16:15:53 Starting...
close logfile如果我对close方法调用进行注释,那么我会得到最后的"exit“行,但是函数永远不会返回。
这是在main的第一行调用的第一行函数中调用的,所以我非常确定我不可能在这一点上搞砸任何事情。我在valgrind上查过了,什么也没找到。
并不是所有的cout调用都只是调试,而不是程序本身的一部分。
发布于 2014-07-31 22:22:37
找到了问题所在。
char* fmtMessage;这是一个未初始化的字符串缓冲区。将其替换为:
char fmtMessage[1024];解决了问题。
如果我想让它再次动态化,我可以假设我需要malloc一些内存来分配给原始的指针定义,或者有更好的方法吗?
https://stackoverflow.com/questions/25041947
复制相似问题