Archived

This topic is now archived and is closed to further replies.

toddhd

Need help with std::bad_alloc error

Recommended Posts

I am trying to read in a previously written binary file, and getting an std::bad_alloc error. I''m still fairly new to C++, and don''t understand what I''m doing wrong. Here is some of the code where I write the binary file: int SaveCharacters() { int size; ofstream ofile("chars.dat", std::ios::binary); //allchars is the vector that holds the character objects size=allchars.size(); //Write the number of chars to save ofile.write((char*)&size , sizeof(size)); for (loop=0;loop<(int)allchars.size();loop++){ size = allchars[loop].Name.length(); ofile.write((char*)&size, sizeof(size)); ofile.write(allchars[loop].Name.c_str(), size); size = allchars[loop].Race.length(); ofile.write((char*)&size, sizeof(size)); ofile.write(allchars[loop].Race.c_str(), size); ... ... void LoadChars(){ ifstream ifile("chars.dat", std::ios::binary); int size; char* value; //find out how many player characters to read int charcount = 0; ifile.read((char*)&charcount, sizeof(charcount)); for(loop=0;(int)loop<(int)charcount;loop++){ ifile.read((char*)&size, sizeof(size)); value = new char[size+1]; memset(value,0,size+1); ifile.read(value,size); CurChar.Name = value; //This next line causes the bad_alloc ifile.read((char*)&size, sizeof(size)); Any ideas what I did wrong? Thanks much...

Share this post


Link to post
Share on other sites
Never mind. A little more education about C++ and binary files taught me that I can just write out the entire Ccharacer object at one time, instead of iterating through every single property. Much easier all around...

Share this post


Link to post
Share on other sites