I am trying to binary serialize the data of vector. In this sample below I serialize to a string, and then deserialize back to a vector, but do not get the same data I started with. Why is this the case?
vector<size_t> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
string s((char*)(&v[0]), 3 * sizeof(size_t));
vector<size_t> w(3);
strncpy((char*)(&w[0]), s.c_str(), 3 * sizeof(size_t));
for (size_t i = 0; i < w.size(); ++i) {
cout << w[i] << endl;
}
I expect to get the output
1
2
3
but instead get the output
1
0
0
(on gcc-4.5.1)
The error is in the call to
strncpy. From the linked page:So, after the first
0byte in the serialized data is found the remainder ofw‘s data array is padded with0s.To fix this, use a
forloop, orstd::copyIMO, instead of using
std::stringas a buffer, just use achararray to hold the serialized data.Example on ideone