Pointers to entities go bad after a while, C++ vector
std::vector<Entity> entities; and the enemies keep an Entity* target. After some spawns, target points to garbage, and it crashes only sometimes. Valgrind says invalid read. Is it because vector moved?
Your discussion
This browser holds the management token for this post.
Save management token
Keep this private. Anyone with the token can resolve or delete this discussion.
4 replies
Yes. push_back reallocates when it runs out of capacity, and all your pointers point into the old buffer. It's the same reason Rust refuses the code in tomasz's thread, /progrider/t/AhtK41Hy5_6g, except here it compiles and you get to find out at runtime.
Say it louder.
Fixes, in the order I'd try them: store an index or a handle in place of a pointer. std::deque if you only add at the ends, its references stay valid on push_back. Calling reserve() up front hides the bug until you exceed it.
Went with index + generation number, so a stale handle gets detected instead of pointing at the wrong enemy. Works well. Thanks, and ferrous, no.