I have a function with the following declaration:
void playCard(string card);
and the following implementation:
void Player::playCard(string card)
{
cout << "Playing " << card << "!" << endl;
// Find iterator representing the card to be played
vector<Card*>::iterator iter;
for(iter = hand.begin(); iter != hand.end(); iter++)
{
if( (*iter)->getName() == card)
continue;
}
// ERROR - Card not found in hand
if(iter == hand.end())
assert(false);
// more stuff
}
The function is called from the following block of code:
// Divide string into 2 words
istringstream iss(in, istringstream::in);
string command, target;
iss >> command >> target;
if(command == "play")
{
players.at(currentTurn)->playCard(target);
}
players is declared as:
vector<Player*> players;
The problem I’m having is that no matter what the “card” string is, I hit the card not found assertion. According to gdb:
Breakpoint 1, Player::playCard (this=0xb3a010, card=0x28ca00) at Player.cpp:138
138 cout << "Playing " << card << "!" << endl;
(gdb) print card
$1 = (string *) 0x28ca00
So within the playCard() function, the card variable is a pointer for some reason. Interestingly enough, the cout statement still displays the contents of the string correctly. Right before calling playCard(), the variable is NOT a pointer according to gdb, just an ordinary string.
Also, this is interesting:
(gdb) print iter
$1 = {_M_current = 0xb9a328}
(gdb) print iter->getName()
Couldn't find method __normal_iterator<Card**,std::vector<Card*, std::allocator<Card*> > >::getName
(gdb) print *iter
$2 = (class Card *&) @0xb9a328: 0xb9a160
(gdb) print *iter->getName()
Couldn't find method __normal_iterator<Card**,std::vector<Card*, std::allocator<Card*> > >::getName
(gdb) print (*iter)->getName()
Program received signal SIGSEGV, Segmentation fault.
0x61111178 in memcpy () from /usr/bin/cygwin1.dll
So gdb causes a segfault when I try to print out that last one, but the same code executes without any segfaults.
I have a feeling I’m dealing with some weird memory issues related to having a vector full of pointers to objects, but I can’t quite put my finger on it.
What’s going on here?
You want
breakinstead ofcontinueinside the loop.They’re kind of similar;
continuemeans continue with the next iteration of the loop,breakmeans break out of the loop.