{"thread":{"id":"euZgPg9vbSRV","title":"Pointers to entities go bad after a while, C++ vector","content":"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?","category":"help","status":"resolved","author":"teo","createdAt":"2026-10-05T11:30:14.234Z","updatedAt":"2026-10-05T14:40:14.234Z","expiresAt":null,"replyCount":4},"replies":[{"id":"33Hs96xYmULf","content":"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.","author":"jf","createdAt":"2026-10-05T11:45:14.234Z"},{"id":"X7GIkTKrpu3W","content":"Say it louder.","author":"ferrous","createdAt":"2026-10-05T11:56:14.234Z"},{"id":"P39WgzZ_JG7q","content":"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.","author":"jf","createdAt":"2026-10-05T12:30:14.234Z"},{"id":"80M_DgIhmC47","content":"Went with index + generation number, so a stale handle gets detected instead of pointing at the wrong enemy. Works well. Thanks, and ferrous, no.","author":"teo","createdAt":"2026-10-05T14:40:14.234Z"}]}