0

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

#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 操作时。

4

3 回答 3

1

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

What you are writing is the actual queue classes themselves, i.e. the class that contains the queue of elements you want to write. Depending on the implementation of queue, you could be writing anything (or not!). For example, if the queue class contains a pointer pointing to an array of elements, you are writing the value of a pointer, but not the elements themselves.

I would recommend serializing (Is it possible to serialize and deserialize a class in C++?) and deserializing your vector of queues.

于 2013-03-30T12:10:08.403 回答
1

What you are doing is essentially equivalent to

memcpy(&here[0], &hello[0], sizeof(queue<unsigned>)*here.size());

So you are making a (shallow) copy of the internal representation of the queues, which includes some pointers. In the destructors of the queues, both the original and the copy try to free the same area of memory. This results in the double free.

The bottom line is: you can't just do a plain shallow memcpy of structures which store pointers and expect it to work.

于 2013-03-30T12:15:31.247 回答
0

You are copying queues as if they where contiguous in memory, and they aren't. Using fwrite, you must copy element by element, because as @reima said, at background you are using memcpy.

Best regards.

于 2013-03-30T18:33:34.797 回答