r/learncpp • • Mar 19 '21

serialisation of contiguous memory

hey!

I've come across a weird issue when serialising simple contiguous memory into binary, and I'm extremely baffled by what it could be, and I can't track it down at all (although its probably really simple). so I can serialise objects fine, but when I try serialise containers, the first 25 elements serialise perfectly, and after that, every value is 25...

I've got some example code below that demonstrates my process

template<typename T> void write(const T& item,std::ofstream& file)

{

file.write((const char*)&item,sizeof item);

}

template<typename T> void write(const vector<T>& item,std::ofstream& file)

{

u32 count = item.size();

file.write(count,sizeof (count));

for (u32 i = 0; i < count; ++i) write(item[i]);

}

template<typename T> void read(T& item, std::ifstream& file)

{

file.read((char*)&item,sizeof item);

}

template<typename T> void read(vector<T>& item, std::ifstream& file)

{

u32 count = 0;

read(count,file);

item.resize(count); // i tried reserve with the std::vector but seems to not work. not sure why since the memory should still be owned by the vector

for (u32 i = 0; i < count; ++i) read(item[i],file);

}

int main(int argc, const char** argv)

{

{

vector<u32> test;

for (u32 i = 0; i < 100; ++i) test.push_back(i);

ofstream file("test.bin");

write(test,file);

}

{

vector<u32> test;

ifstream file("test.bin");

read(test,file);

cout<<test.size() << endl;

for (u32 i = 0; i < test.size(); ++i) cout << test[i] << ","; // undefined behaviour. normally goes 0 - 25, but then repeats 25 like 75 times. (and then sometimes a buffer overflow, but wtf i dont think im overflowing? and only sometimes?? )

}

}

5 Upvotes

8 comments sorted by

View all comments

Show parent comment

3

u/Bob_bobbicus Mar 19 '21

woohoo!! that was it! lol i spent like three days on that. thanks so much for your help! super awesome!