Ofstream::write()未处理异常

ofstream::write() unhandled exception

本文关键字:未处理 异常 write Ofstream      更新时间:2023-10-16

所以我正在编写一个日志库,用于记录各种各样的事情,当我对它运行测试时,它一直崩溃。当我将日志消息写入ofstream文件时,我将异常缩小到写入函数。我解析消息和其他东西,然后对ofstream::write()进行实际调用。这里是我得到一个重新运行时错误的部分:

void Logger::writeMessage(LogMessage* message)
{
    if(message==NULL)
        return;
    char buffer[MAX_PATH];
    switch(message->GetMessageType())
    {
    case LOGMESSAGE_HEADER:
        sprintf(buffer, m_logInfo->headerFormat, message->GetMessage().c_str());
        break;
    case LOGMESSAGE_FOOTER:
        sprintf(buffer, m_logInfo->footerFormat, message->GetMessage().c_str());
        break;
    case LOGMESSAGE_DEBUG:
        sprintf(buffer, "%s %s", m_logInfo->debugPrefix.c_str(), message->GetMessage().c_str());
        break;
    case LOGMESSAGE_ADDRESS:
        sprintf(buffer, "%s %s", m_logInfo->addressPrefix.c_str(), message->GetMessage().c_str());
        break;
    case LOGMESSAGE_VALUE:
        sprintf(buffer, "%s %s", m_logInfo->valuePrefix.c_str(), message->GetMessage().c_str());
        break;
    case LOGMESSAGE_CUSTOM:
    default:
        sprintf(buffer, "test!", message->GetMessage().c_str());
        break;
    }
    try
    {
        if(!m_ofile.is_open() || !m_ofile.good())
            return;
        //string formattedMessage(buffer);
        //formattedMessage.append(m_logInfo->lineTerminator);
        string result;
        if(message->IsUsingTimestamp())
        {
            m_ofile << message->GetTimeStamp().GetTimeString().c_str() << " ";
            //result.append(message->GetTimeStamp().GetTimeString());
            //result.append(" ");
        }
        m_ofile << buffer << m_logInfo->lineTerminator;
        //result.append(formattedMessage);
        //result.push_back('');
        //m_ofile.write(result.c_str(), MAX_PATH);
        //m_ofile << result.c_str();
    } 
    catch(std::exception &e)
    {
        MessageBox(NULL, e.what(), "ERROR", NULL);
    }
}
如您所见,我在try catch块中调用了

,我甚至检查了文件是否有效并打开。当我在调用及其周围设置断点时,调用工作得很好,但是一旦它到达函数的末尾,它会给我这个:

LoggerTest.exe中0x773515ee的未处理异常:0xC0000005:访问违规写入位置0xfeeeee .

,然后显示在xlock.cpp中的这个函数中发生的错误:

__thiscall _Lockit::_Lockit(int kind)
    : _Locktype(kind)
    {   // lock the mutex
    if (_Locktype < MAX_LOCK)
        _Mtxlock(&mtx[_Locktype]);
    }

我的猜测是我有一个坏的字符串或指针,但我不能确定它。

注意:我试着做

m_ofile << "test!";

现在它在这里给我assert失败:_ASSERTE(_CrtIsValidHeapPointer(pUserData));

.c_str()函数返回一个指针,这可能导致ostream输出出现问题。

除非有必要在代码块之外转换它,否则只需传递<<结果,而不将其转换为c字符串,看看是否解决了您的问题。