std::vector resize vs reserve during fread

2019-03-06 04:48发布

问题:

This is my working code:

size_t FileReader::Read(ByteVector& output)
{
    output.resize(m_elementSize * m_blockSize);
    size_t read = fread(&output[0], m_elementSize, m_blockSize, m_file);
    output.resize(read);
    return read;
}

However previous I have tried code which had output.reserve(m_elementSize * m_blockSize);

As far as I know reserve just founds place in memory for container. resize do the same, also changes memory from trash to some given values and change container size.

fread first parameter is void * and it is the same as unsigned char *, my question, why did I get exception while calling fread.

Why is it happening? Because fread takes void pointer and it do not write into memory using vector class.

P.S. forgot to mention typedef std::vector<unsigned char> ByteVector

回答1:

If the vector is initially empty, then output[0] invokes undefined behaviour (regardless of how much space you have reserved), and on some platforms it may throw an exception.



回答2:

Have found the problem, now I use code I called working

I wanted to avoid unnecessary resize because it works with data in memory, however after reserve output[0] do not exists.

What is more after read vector size would be zero and resize would destroy read data.