Advertisement

Inserting element into vector during iteration causes crash

Started by September 20, 2016 10:17 AM
12 comments, last by Khatharr 8 years, 3 months ago

It does do exactly that. But you also call resize(10), which changes the vector to have 10 elements, and since you only had 10 capacity, it's full up again.

Ahh okay, but when I remove the resize(10) I still get the crash, so I am a bit confused now...

I thought this sort of thing would be quite common in C++ so am surprised at this behavior!


Documentation of std::vector will point out that element insertion invalidates iterators.

It looks like this vector is a primary owner for these objects. If you can ensure that the vector outlives anything that may refer to its contents then you could just use std::vector<Test1> and then take references to elements or (preferably) simply refer to them directly as needed. If you're thinking about polymorphism then that won't work though.

The actual situation in my game needs polymorphism, thanks though!

Thanks everyone for your input I am learning a lot!

Ahh okay, but when I remove the resize(10) I still get the crash

Why do you reserve space for exactly 10 elements?

You double your m_test vector content with each update loop.

If you reserved space for 10 elements and there's already 5 elements in m_test, then you can run update just once. Next iteration will fail.

And if there's already more than 5 existing elements in m_test, then update loop will fail, because doubled vector content won't fit in reserved 10 elements.

And even if you will reserve memory before each update to allow your loop run many times, you'll consume entire ram in ~10-20 updates, depending on available ram size and its fragmentation.

Advertisement

Ahh okay, but when I remove the resize(10) I still get the crash, so I am a bit confused now...


I don't think you'll see it on the first push_back, but you will probably see it on the eleventh. If that's not what you experience, post your code.

Beyond that, if you're still stuck for how to proceed in the general case, there are a few suggestions above:
a) postpone additions until the end of the loop (e.g. by adding to a separate temporary vector),
b) switch to std::deque which allows push_back during iteration,
c) restart iteration from the beginning any time you push_back
d) call reserve() once (and only once) with the maximum capacity, and take steps to ensure you never exceed that

If we know more about the requirements of the real case then we can provide more specific advice.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement