2
votes

is there anybody using BWAPI who gets access violation error when accessing the Unit objects of the current game?

i am certain that the error is not in my code.. anyway.. is there anything i can do to avoid access violation?

i am getting this error sometimes at line with the comment bellow.. this code bellow execute many times and only sometimes i get the error..

int Squad::getSize() {

    int no = 0;

    for (int i = 0; i < (int) agents.size(); i++) {

        BaseAgent* agent = agents.at(i);

        if (agent != NULL && agent->isAlive() && agent->getUnit() != NULL && !agent->getUnit()->isBeingConstructed()) // this line
            no++;
    }

    return no;
}

this is the code that I use to remove an BaseAgent from the vector.. analyze that and see if i can do it better:

void AgentManager::cleanup() {

    //Step 2. Do the cleanup.
    int cnt = 0;
    int oldSize = (int)agents.size();
    for (int i = 0; i < (int)agents.size(); i++) {

        if (!agents.at(i)->isAlive()) {

            delete agents.at(i);

            agents.erase(agents.begin() + i);
            cnt++;
            i--;
        }
    }

    int newSize = (int)agents.size();
}

the BaseAgent code is on this link

1
Why not try checking pointers for NULL? - Alexander Chertov
i ve already done.. is not a null pointer.. - thiagoh
Terran imba, just saying - tenfour
You are missing a NULL check for agent->getUnit(). - juanchopanza
@juanchopanza i ve already done that also.. i removed from code because the problem isnt that - thiagoh

1 Answers

1
votes

I would speculate that this line:

BaseAgent* agent = agents.at(i);

is returning some invalid pointer which is not set to 0.

Looking at your cleanup code, it looks a bit complicated. I would suggest

  1. looping over the entire vector, deleting the dead elements and setting the pointers to 0.

  2. After the loop, use the erase-remove idiom to remove all NULL pointers from the vector.

step 1

for (unsigned int i = 0; i < agents.size(); ++i) {
    if (!agents.at(i)->isAlive()) {
       delete agents.at(i);
       agents.at(i) = 0;
}

step 2

agents.erase(std::remove(agents.begin(), agents.end(), 0), agents.end());