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

代码如下:

//************//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但是程序结束,就报错。
可能是内存泄漏的问题,不确定自己写的对不对。

回答

出问题的代码是:

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类型不行。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Scroll Up