返回指针时出现运行时错误

Runtime Error upon returning pointer

这是一个从文件中读取二进制数据然后 returns 指向对象的指针的方法。

Database* Database::open(const char *path)
{
    ifstream ifs;
    ifs.open(path, ios::in | ios::binary);
    if(!ifs)
    {
        cerr << "Failed to open database." << endl;
        return NULL;
    }
    config_vars cfg;
    ifs.read((char*)&cfg, sizeof(config_vars));
    if ( (ifs.rdstate() & std::ifstream::failbit ) != 0 )
    {
        cerr << "Failed to read database file." << endl;
        return NULL;
    }
    ifs.close();

    Database *db = new Database();
    db->config = cfg;
    db->db_path = string(path);
    return db;
};

调用堆栈显示,它是通过销毁config_vars结构体的字符串成员来指示的,其定义如下:

struct config_vars
{
    string name;
    string author;
    int date;
};

我真的不明白是什么导致了访问冲突。如果重要的话,该方法也是静态的。

调用堆栈:

msvcp100d.dll!std::_Container_base12::_Orphan_all()  Line 201 + 0x12 bytes  C++
    NoDB.exe!std::_String_val<char,std::allocator<char> >::~_String_val<char,std::allocator<char> >()  Line 478 + 0xb bytes C++
    NoDB.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::~basic_string<char,std::char_traits<char>,std::allocator<char> >()  Line 754 + 0xf bytes C++
    NoDB.exe!config_vars::~config_vars()  + 0x54 bytes  C++
>   NoDB.exe!Database::open(const char * path)  Line 24 + 0x1b bytes    C++

std::stringclass只不过是一个带指针的数据成员而已。因此,无论您使用 ifs.read((char*)&cfg, sizeof(config_vars)); 读入 cfg 都是将指针设置为完全无效的指针。这就是您的访问冲突的根源。

您需要做的是单独阅读 cfg 的每个成员。根据 cfg 文件的格式,您可以执行如下操作:

ifs >> cfg.name;
ifs >> cfg.author;
ifs >> date;

但这可能不会那么容易。

无论如何,这就是您遇到访问冲突的原因。您需要找到一种不同的方式,但这将是一个不同的问题!祝你好运!

C++ 对象不是字符串。它们不仅仅是字节的平面集合。通常,您不能以这种方式反序列化它们。您将需要一个适当的序列化库。