简体   繁体   中英

C++ : Double free or corruption (out)

I'm getting this error

*** Error in `./main': double free or corruption (out): 0x000000000095c8a0 ***
  • getPieces() is defined as vector<Piece*> Position::getPieces()
  • getSymbol() returns an int

What I want to acheive is to remove from the vector the Piece pointer that is the same as variable Pointer* piece .

int Position::removePiece(Piece* piece) {
  for (size_t i = 0; i < getPieces().size(); i++) {
    if (getPieces()[i] == piece) {
      getPieces().erase(getPieces().begin() + i); // errors happens here
      std::cout << getPieces().size() << std::endl;
      return getSymbol();
    }
  }

  return -1;
}

As written, getPieces() returns a copy of a vector. Each time you call getPieces() , it's a different copy. You try to remove element from one vector using iterator from another, no wonder something goes wrong. Anyway, you try to modify a copy which will be destroyed when you leave the function (or even earlier).

If getPieces is a method of Position returning copy of internal field (say, m_vector ), use m_vector in removePiece() instead of getPieces calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM