是什么原因导致这里出现分段错误/munmap_chunk():无效指针错误?

发布于 2025-01-20 01:58:07 字数 1134 浏览 5 评论 0原文

这段代码中分段错误的原因是什么?为什么有时会出现 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文