在windows上使用std::stringstream时发生访问冲突

Access violation when using std::stringstream on windows

本文关键字:stringstream 访问冲突 std windows      更新时间:2023-10-16

我目前正在实现一个基本的文件加载函数。当使用std::stringstream时,程序会因stringstream析构函数中的访问冲突而崩溃。下面是函数:

void macro_storage_t::load(std::string filename)
{
    std::ifstream file(filename);
    if (file.is_open())
    {
        clear();
        char line_c[4096];
        while (file.getline(line_c, 4096))
        {       
            std::string line(line_c);
            if (line.find("VERSION") == std::string::npos)
            {
                std::stringstream ss(std::stringstream::in | std::stringstream::out);
                int a, b, c, d;
                ss << line;
                ss >> a >> b >> c >> d;
                entry_t entry;
                entry.timestamp = a;
                entry.type = static_cast<entry_type_t>(b);
                entry.button = static_cast<button_t>(c);
                entry.key = static_cast<BYTE>(d);
            }
        }
    }
}

它加载的文件看起来像这样(为了更好的可读性而缩短):

VERSION 1
0 14 254 0

,并通过以下函数保存:

void macro_storage_t::save(std::string filename)
{
    std::ofstream file(filename, std::ios::trunc);
    if (file.is_open())
    {
        file << "VERSION " << MACRO_VERSION << std::endl;
        for (std::vector<entry_t>::iterator it = entry_list_.begin(); it != entry_list_.end(); ++it)
        {
            entry_t entry = *it;
            file << (int)entry.timestamp << " " << (int)entry.type << " " << (int)entry.button << " " << (int)entry.key << std::endl;
        }
        file.close();
    }
}

错误是:

Unhandled exception at 0x0f99a9ee (msvcp100d.dll) in FLAP.exe: 0xC0000005: Access violation reading location 0x00000004.

一旦stringstream被隐式删除,错误就会发生…

我在Windows 7上使用Visual Studio 2010

试试这个:

void macro_storage_t::load(std::string filename)
{
    std::ifstream file(filename);
    if (file.is_open())
    {
        clear();
        std::string line;
        if (std::getline(file, line))
        {       
            if (line.substr(0, 8) == "VERSION ")
            {
                // optional: read the actual version number from the line,
                // if it affects how the following values must be read...
                while (std::getline(file, line))
                {
                    std::istringstream ss(line);
                    int a, b, c, d;
                    if (ss >> a >> b >> c >> d)
                    {
                        entry_t entry;
                        entry.timestamp = a;
                        entry.type = static_cast<entry_type_t>(b);
                        entry.button = static_cast<button_t>(c);
                        entry.key = static_cast<BYTE>(d);
                        entry_list_.push_back(entry);
                    }
                }
            }
        }
    }
}