是什么原因导致这里出现分段错误/munmap_chunk():无效指针错误?
这段代码中分段错误的原因是什么?为什么有时会出现 munmap_chunk() 错误,有时会出现 seg 错误?
我们是否无法按照代码所示存储/检索对象?获得类似结果的推荐方法是什么?
预期:
将 test1 对象存储到文件名“data”中
从文件“data”中检索数据并存储到 test2 对象中
#include <iostream>
#include <fstream>
class Test{
int num1;
std::string str1;
public:
void get_info(){
std::cout<< "Enter str1: ";
std::cin >> str1;
std::cout << "Enter num1: ";
std::cin >>num1;
}
void store_info(){
std::ofstream file;
file.open("data",std::ios::app);
file.write((char *)this, sizeof(Test));
}
void display(){
std::cout << "Str1: "<< str1 << std::endl;
std::cout << "Num1: "<< num1 <<std::endl;
}
void retrieve_info(){
std::ifstream file;
file.open("data");
file.read((char *)this, sizeof(Test));
}
};
int main(){
Test test1;
test1.get_info();
test1.display();
test1.store_info();
Test test2;
test2.display();
test2.retrieve_info();
test2.display();
}
What is the cause of segmentation fault in this code? Why do I sometimes get munmap_chunk() error and sometimes seg fault?
Are we not able to store / retrieve the objects as shown in the code? What would be a recommended method to achieve a similar result?
Expected:
stores test1 object into a file name "data"
retrieves data from file "data" and stores into test2 object
#include <iostream>
#include <fstream>
class Test{
int num1;
std::string str1;
public:
void get_info(){
std::cout<< "Enter str1: ";
std::cin >> str1;
std::cout << "Enter num1: ";
std::cin >>num1;
}
void store_info(){
std::ofstream file;
file.open("data",std::ios::app);
file.write((char *)this, sizeof(Test));
}
void display(){
std::cout << "Str1: "<< str1 << std::endl;
std::cout << "Num1: "<< num1 <<std::endl;
}
void retrieve_info(){
std::ifstream file;
file.open("data");
file.read((char *)this, sizeof(Test));
}
};
int main(){
Test test1;
test1.get_info();
test1.display();
test1.store_info();
Test test2;
test2.display();
test2.retrieve_info();
test2.display();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论