返回指针时运行时错误

Runtime Error upon returning pointer

本文关键字:运行时错误 指针 返回      更新时间:2023-10-16

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

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::string 类只不过是一个带有指针的数据成员。 因此,无论您使用 cfg 读入 cfg ifs.read((char*)&cfg, sizeof(config_vars)); 是什么,都将指针设置为完全无效的指针。 这就是访问冲突的根源。

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

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

但这可能不会那么容易。

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

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