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.
sizeof
doesn't do what you think it does for the vector
. If you want to get the size, in bytes, of the allocated memory for the vector, you can do index.size() * sizeof(size_t)
. index.size()
is the number of elements in the vector, and sizeof(size_t)
is the size of one element in the vector.
The corrected code would be more like (trimming extra stuff):
// writing...
std::vector<size_t> index;
size_t numElements = index.size();
size_t numBytes = numElements * sizeof(size_t); // get the size in bytes
ofs.write((char *) &index[0], numBytes);
// reading...
std::vector<size_t> index;
index.resize(numElements);
ifs.read((char *) &index[0], numBytes); // again, numBytes is numElements * sizeof(size_t)
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:
int* array = new int[500];
// sizeof(array) is the size of the pointer, which is likely 4 or 8 bytes if you're on 32 or 64 bit system
I would try to use a pointer to a vector. You are trying to use a reference to a data type. It might not work if your C++ is trying to be typesafe
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.