0

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why does it invoke UB?
If the vector is empty it doesn't have a zeroth element. Attempting to access a non-existent element is UB.
Not sure, but I think it should always throw an exception, doesn't it?
Nope. It's equivalent to *(output.begin()), which involves dereferencing a beyond-the-end iterator, which is always undefined behaviour. Throwing an exception is allowed (but then so is anything else) and absolutely nothing is required. You can call output.at(0) if you want an exception.
1

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.

1 Comment

resize won't do anything if you pass it the current size of the vector, so your if is unnecessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.