Pointers to objects in a std::vector corrupting after using push_back on the vector

In main.cpp, I have a vector of Entities:

std::vector<Entity> entities = {};

And each entity has a pointer to another entity (its target):

Entity* target = nullptr;

The entity gets a picks a random enemy from the vector passed as a reference:

entity.hpp:

void Entity::update(std::vector<Entity> &entities){

    // new target if no target
    if (target == nullptr){

        if (entities.size() > 1){

            std::uniform_int_distribution<int> index_dist(0, entities.size() - 1);
            
            while (true){
                target = &(entities.at(index_dist(rand_generator)));

                if (!isSameEntity(target)){
                    break;
                }
            }

        }

    }

    if (target != nullptr){

        // move towards target
        float dist_x = (x + radius) - (target->x + target->radius);
        float dist_y = (y + radius) - (target->y + target->radius);
        float distance = sqrt(pow(dist_x, 2) + pow(dist_y, 2));
        if (abs(distance - (radius + target->radius)) > 1){
            std::cout << id << "=>" << target->id << "\n";
            float rad = radians(angle(x, y, target->x, target->y));
            float x_vel = sin(rad);
            float y_vel = cos(rad);
            // std::cout << "targ: " << id << "->" << target->id << "    " << target->x << "|" << target->y << "\n";
            x += x_vel;
            y += y_vel;
        }

        // try to attack target

        // check if target is dead
        if (target->health <= 0){
            target = nullptr;
        }

    }
    
    // render
    rect = {int(x), int(y), radius * 2, radius * 2};
    centerRect(rect);
    SDL_RenderCopy(renderer, texture, NULL, &rect);
}

main.cpp:

        entities.erase(
            std::remove_if(
                entities.begin(), entities.end(),
                [&entities](Entity &entity){
                    entity.update(entities);
                    return entity.health <= 0;
                }
            ),
            entities.end()
        );

And when I add a new entity to the vector, some of the target ids become a random large integer like 2127259440 (an entity's id should be 1 more than the last entity's id).

When I don't push_back a new entity to the vector, everything runs fine, but when I add a few more entities to the vector using push_back, some target ids go haywire.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum