Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c++ - vector serialization

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is in the call to strncpy. From the linked page:

If the length of src is less than n, strncpy() pads the remainder of dest with null bytes.

So, after the first 0 byte in the serialized data is found the remainder of w's data array is padded with 0s.

To fix this, use a for loop, or std::copy

std::copy( &s[0], 
           &s[0] + v.size() * sizeof(size_t), 
           reinterpret_cast<char *>(w.data()) );

IMO, instead of using std::string as a buffer, just use a char array to hold the serialized data.

Example on ideone


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...