开发者

binary read/write runtime failure

I've looked at binary reading and writing objects in c++ but are having some problems. It "works" but in addition I get a huge output of errors/"info".

What I've done is

Person p2;

std::fstream file;
file.open( filename.c_str(), std::ios::in | std::ios::out | std::ios::binary );
file.seekg(0, std::ios::beg );
file.read ( (char*)&p2, sizeof(p2));
file.close();
std::cout << "Name:开发者_运维问答 " << p2.name;

Person is a simple struct containing string name and int age. When I run the program it outputs "Name: Bob" since I have already made a program to write to a file (so the object is already in filename).

IN ADDITION to outputting the name it also outputs:

* glibc detected * program: double free og corruption (fastttop): ***

Backtrace:

...

Memory map:

...

Abort


Is the name string in the Person struct a character array or a STL string? You can't fill in an STL String by binary reading data over top of it, since the data format is not serializable (contains pointers)


It would be interesting to see how you write the information to file as well, as well as how the Person struct is built.
If you don't have any problem that the file is plain text, my suggestion would be to write to file using string::c_str() (which returns a const char*) as well as using itoa() or itoa_s() to get the integer as a char*.

You can also have one or several constructors in Person:

Person(const std::string& name, int age);  
Person(const char* name, int age);

then, when you extract the data from the file you just call the constructor with that data.


Either p2.name is a char* and you are writing and reading the pointer value, not what is pointed by it. Or p2.name is a more complex type such as std::string which is using internaly pointers with the same problem.

Serializing classes often need more work than just dumping the memory representation.


You said you wrote the Person object to a file. Did you tried to use a dump tool to see if what you have inside the file is what you are expecting?

Also did you tried to instead of using string, use a ordinary char (as @bdk pointed out) ?


When you use binary IO, the size must be fixed. If you use STL string here, it would have a problem as the size of a STL string is arbitrary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜