std::vector resize vs reserve during fread

匆匆过客 提交于 2019-12-20 07:27:19

问题


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.



来源:https://stackoverflow.com/questions/18357440/stdvector-resize-vs-reserve-during-fread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!