c++ - ofstream 关​​闭导致程序崩溃

标签 c++ stream crash ofstream

我有以下代码

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 方法调用进行评论,那么我会得到最终的“退出”行,但该函数永远不会返回。

这是在 main 的第一行调用的函数的第一行调用的,所以我相当确定到那时我不会把任何事情搞砸得太严重。 我确实通过 valgrind 运行了它,但什么也没发现。

并不是所有的 cout 调用都只是调试,而不是程序本身的一部分。

最佳答案

发现问题了。

char* fmtMessage;

这是一个未初始化的字符串缓冲区。替换为:

char fmtMessage[1024];

解决了问题。

如果我想再次使其动态化,我可以假设我需要分配一些内存来分配给原始指针定义,还是有更好的方法?

关于c++ - ofstream 关​​闭导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041947/

相关文章:

c# - .net 自定义表单甚至处理程序从不同的线程调用并崩溃 VS

c++ - 将一个数组分配给另一个数组 C++

c++ - QProcess with non-wrapped pipe symbol |在参数列表中

Java 无法将输出流保存到文件

android - 切换 Activity 会导致Android应用崩溃

ruby-on-rails - 由于意外中断,Rails Server和控制台崩溃(LocalJumpError)

c++ - 编译检查是否编译为静态库

c++ - 与所有其他编译器一起使用的MSVC错误C2280(试图引用已删除的功能)

ruby - 使用 Rack 将网络上传流式传输到套接字

algorithm - Scala 流上的归纳证明