不会coding 2020-06-27 16:00 采纳率: 100%
浏览 573
已采纳

程序正常输出,退出时显示“写入位置 0xDDDDDDDD 时发生访问冲突”。

程序能正常输出,直到最后退出程序的时候报错。图片说明

代码如下:

//************//binary_serialization.h
namespace binary_space {
    template<class T>
    extern bool serialize(T& n0, const char filename[]); 

    template<class T>
    extern bool deserialize(T& n1, const char filename[]);
}

//************//binary_serialization.cpp
#include "binary_serialization.h"
#include <fstream>
using namespace binary_space;
template<class T>
bool  binary_space::serialize(T& n0, const char filename[]) {
    FILE *fp = fopen(filename, "rb+");
    if (!fp)
    {
        fp = fopen(filename, "w");
        if (!fp) {
            std::cout << "Can not open the file named " << filename << std::endl;
            return false;
        }
    }
    fwrite(&n0, sizeof(n0), 1, fp);
    fclose(fp);
    return true;
}

template<class T>
bool binary_space::deserialize(T& n1, const char filename[]) {
    FILE *fp = fopen(filename, "rb+");
    if (!fp)
    {
        std::cout << "Can not open the file named " << filename << std::endl;
        return false;

    }
    fread(&n1, sizeof(n1), 1, fp);
    fclose(fp);
    return true;
}


//************//Main.cpp
struct vector_test{
    std::vector<int > myint;
};
int main(){
    vector_test my_vector;
    //结构vector_test 里面包含一个vector,下面为赋值
    my_vector.myint.push_back(0);
    my_vector.myint.push_back(1);
    my_vector.myint.push_back(2);
    bool check_s=binary_space::serialize(my_vector, "vector.txt");
    //将一个结构写入一个文件
    if (check_s == false) {
        return 0;
    }
    vector_test my_vector2;
    binary_space::deserialize(my_vector2, "vector.txt");
    //从文件中读取这个类,实现在.cpp里面
    //以下为输出
    std::cout << my_vector2.myint[0] << std::endl;
    std::cout << my_vector2.myint[1] << std::endl;
    std::cout << my_vector2.myint[2] << std::endl;
    //test vector  end

}

问题是,能正确输出0,1,2但是程序结束,就报错。
可能是内存泄漏的问题,不确定自己写的对不对。

  • 写回答

1条回答 默认 最新

  • Frank_Liuxing 2020-06-27 20:04
    关注

    出问题的代码是:

    template<class T>
    bool binary_space::deserialize(T& n1, const char filename[]) {
        FILE *fp = fopen(filename, "rb+");
        if (!fp)
        {
            std::cout << "Can not open the file named " << filename << std::endl;
            return false;
    
        }
        fread(&n1, sizeof(n1), 1, fp);
        fclose(fp);
        return true;
    }
    
    

    你是不能把一个vector的内存地址保存到文件,再从文件中恢复。
    使用你这种直接将内存写文件的方法,只有**POD**类型可以保证成功,非POD类型不行。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键