I’m trying to do some quick and dirty vector serialization, which doesn’t work as expected. The problem is a segfault when trying to read the vector from a file. I store the file offset and vector size in the header. Here’s the code:
// writing
std::vector<size_t> index;
header.offset = ofs.tellp();
header.size = sizeof(index);
ofs.write((char *) &index[0], sizeof(index)); // pretty bad right, but seems to work
// reading
std::vector<size_t> index;
index.resize(header.numElements)
ifs.seekg(header.offset);
// segfault incoming
ifs.read((char *) &index[0], header.size);
To be honest I’d surprised if this worked, but I’m not sure what is a proper way to achieve what I want. I’d prefer to stay away from boost, but I’m already using Qt so if QVector or QByteArray would help me somehow I could use these.
sizeofdoesn’t do what you think it does for thevector. If you want to get the size, in bytes, of the allocated memory for the vector, you can doindex.size() * sizeof(size_t).index.size()is the number of elements in the vector, andsizeof(size_t)is the size of one element in the vector.The corrected code would be more like (trimming extra stuff):
As for what
sizeof(index)really does, it returns the size of the actual vector object. The elements the vector stores are separate from its size. For example: