I’m making a simple command line Hangman game.
void Hangman::printStatus()
{
cout << "Lives remaining: " << livesRemaining << endl;
cout << getFormattedAnswer() << endl;
}
string Hangman::getFormattedAnswer()
{
return getFormattedAnswerFrom(correctAnswer.begin(), correctAnswer.end());
}
string Hangman::getFormattedAnswerFrom(string::const_iterator begin, string::const_iterator end)
{
return begin == end? "" : displayChar(*begin) + getFormattedAnswerFrom(++begin, end);
}
char Hangman::displayChar(const char c)
{
return c;
}
(Eventually, I’ll change this so displayChar() displays a - or a character if the user has guessed it, but for simplicity now I’m just returning everything.)
When I build and run this from VS 2010, I get a popup box:
Debug Assertion Failed!
xstring Line: 78
Expression: string iterator not
dereferenceable
What am I doing wrong?
The problem is in the evaluation of:
In executing this statement, it is evident that your compiler is first incrementing
begin, returning the “next”beginfor use as the first argument togetFormattedAnswerFrom, and then dereferencingbeginfor the argument todisplayChar.When
beginis one behindend, thenbegin != endsodisplayChar(*begin) + getFormattedAnswerFrom(++begin, end)will run. Your compiler incrementsbegin, so nowbegin == end, and the dereference ofbeginis invalid.See also: Order of evaluation in C++ function parameters