返回指针时运行时错误
Runtime Error upon returning pointer
这是一个从文件中读取二进制数据然后返回指向对象的指针的方法。
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++对象不是字符串。它们不仅仅是字节的平面集合。通常,您不能以这种方式反序列化它们。您将需要一个适当的序列化库。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 运行时错误:引用绑定到类型为"int"的空指针
- 运行时错误:基0x000000000000溢出到0xffffffffffffffff的指针索引表达式 (basic_st
- 在指向矢量的智能指针上使用 push_back() 时运行时错误
- C 代码的运行时错误(基于指针)
- 使用MAP指针时运行时错误
- C 指针运行时错误
- C++指针运行时错误 - 使用指针设置变量然后检索
- 返回指针时运行时错误
- 访问指针类成员变量c++时发生运行时错误
- 成员函数指针运行时错误——ESP的值在函数调用中没有正确保存
- 运行时错误C++程序:检测到glibc,munmap_chunk(),指针无效
- 内存运行时错误:我们在哪里删除这个指针
- 传递派生类指针时的运行时错误
- 数组和指针 - 运行时错误
- c++对象指针的优先级队列在运行时错误为无效堆
- 指向结构的指针出现运行时错误
- 检查指针是否为NULL并导致运行时错误