c++ - Unhandled exception at 0x50E2DF58 (msvcp120d.dll) -
i'm trying read binary file structs. error thrown when program exits. breakpointed , error comes after return 0 executed.
when run program displays results. not crash until after system("pause")
this actual error: unhandled exception @ 0x50e2df58 (msvcp120d.dll) in struct reader.exe: 0xc0000005: access violation reading location 0x007ab1ec.
#include <iostream> #include <string> #include <fstream> using namespace std;  struct user{     string name; };  int main(){     fstream file("file.dat", ios::in | ios::binary);     user users[5];      (size_t = 0; !file.eof(); i++)     {         file.read(reinterpret_cast<char *>(&users[i]), sizeof(user));     }      file.close();     size_t size = (sizeof(users) / sizeof(user));      (size_t = 0; < size; i++)     {         cout << users[i].name << endl;     }      system("pause");     return 0; } 
when return function, destructor each element of users array executed.
the users array contains 5 user objects, each of contain std::string.
std::string objects abstract heap allocated memory, use buffer contain each character of string contain.
when perform binary write onto each element of users array, you're setting internal pointer(s) of std::string instances garbage.  when destructors called try read through garbage pointer, and/or free garbage pointer.
at rate, it's bad business.
to fix problem, need implement mechanism serializing/deserializing strings, copying raw bytes of objects isn't going cut it.
Comments
Post a Comment