Vector serialization

I am trying to binary serialize vector data. In this example below, I serialize the string and then deserialize back to the vector, but do not get the same data I started with. Why is this so?

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 a way out

1  
2
3

but instead we get the conclusion

1
0
0

(on gcc-4.5.1 )

+5
source share
4 answers

Error while calling strncpy. On the linked page:

If src is less than n, strncpy () fills the remainder of dest with zero bytes.

So, after the first byte 0in the serialized data is found, the rest of the data array is wpadded with 0s.

To fix this, use a loop fororstd::copy

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

IMO, std::string , char .

ideone

+4

strncpy - . , size_t , NULL, . BE, 0. std::copy.

+2

, int , ascii , int .

, , 10 ,

// create temporary string to hold each element
char intAsString[10 + 1];

sprintf(intAsString, "%d", v[0]);

itoa( v[0], intAsString, 10 /*decimal number*/ );

ostringstream <

if you look at the contents of the memory intAsString and v [0], they are very different from each other, the first ones contain the letters ascii, which represent the value v [0] in the decimal number system (base 10), and v [0] contains the binary representation of the number (because how computers store numbers).

-1
source

The safest way would be to simply scroll the vector and save the values ​​separately into a char array of size 3 * sizeof (size_t). Thus, you have no dependence on the internal structure of the implementation of the vector class.

-1
source

All Articles