Reputation: 69
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;
}
Upvotes: 1
Views: 2052
Reputation: 1572
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.
Upvotes: 2