gpt4 book ai didi

c++ - 在 C++ 中使用 fread 时出现双重释放或损坏错误

转载 作者:行者123 更新时间:2023-11-28 03:20:01 27 4
gpt4 key购买 nike

所以基本上我是在编写一个测试程序,看看我是否可以分别使用 fwrite 和 fread 将队列 vector 写入和读取到二进制文件中。即使读取和写入部分正确完成并且值正确,我也会收到双重释放或损坏错误。测试代码如下

#include <stdio.h>
#include <vector>
#include <queue>

int main(){

vector<queue<unsigned> > hello(17);
vector<queue<unsigned> > here(17);
queue<unsigned> temp;
for(int f=0;f<4;f++){//initialise a random queue
temp.push(f);
}
for(int i=0;i<hello.size();i++){//assign random queue to every index of vector
hello[i]= temp;
}
FILE *fo;
fo = fopen("hello","wb");
fwrite(&hello[0],sizeof(queue<unsigned>),hello.size(),fo);
fclose(fo);
printf("Writing done!\n");

FILE *fi;
fi=fopen("hello","rb");
fread(&here[0],sizeof(queue<unsigned>),here.size(),fi);
fclose(fi);
printf("Reading done!\n");
for(int i=0;i<here.size();i++){
printf("At key %d value at front is is %d",i,here[i].front());
here[i].pop();
printf(" value %d ",here[i].front());
here[i].pop();
printf(" value %d\n",here[i].front());
}
}

错误似乎是在执行 fread 操作时。

最佳答案

fread 和 fwrite 将原始指针作为它们的第一个参数。在每种情况下,您传入的是队列的地址(名为 hello 的队列 vector 中的第一个元素和名为 here 的队列 vector 的第一个元素。

您正在编写的是实际的队列类本身,即包含您要编写的元素队列的类。根据队列的实现,你可以写任何东西(也可以不写!)。例如,如果队列类包含指向元素数组的指针,则您写入的是指针的值,而不是元素本身。

我会建议序列化 ( Is it possible to serialize and deserialize a class in C++? ) 和反序列化您的队列 vector 。

关于c++ - 在 C++ 中使用 fread 时出现双重释放或损坏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15718315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com