I'm working off of a tutorial to learn C++ using the most recent version of Visual Studio Community 2017 on an updated version of Windows 8.1.
When I adjusted the following .cpp file and ran the program it crashed after entering an input with the error:
Debug Assertion Failed!
Program C:\WINDOWS\SYSTEM32\MSVCP140D.dll File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.11.25503\include\xstring Line: 2969
Expression string subscript out of range
#include "stdafx.h"
#include "FBullCowGame.h"
using int32 = int;
FBullCowGame::FBullCowGame() { Reset(); }
int32 FBullCowGame::GetMaxTries() const { return MyMaxTries; }
int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; }
void FBullCowGame::Reset()
{
constexpr int32 MAX_TRIES = 8;
MyMaxTries = MAX_TRIES;
const FString HIDDEN_WORD = "ant";
MyHiddenWord = HIDDEN_WORD;
MyCurrentTry = 1;
return;
}
bool FBullCowGame::IsGameWon () const { return false; }
bool FBullCowGame::CheckGuessValidity(FString)
{
return false;
}
// Receives a VALID guess, increments turn, and returns count
FBullCowCount FBullCowGame::SubmitGuess(FString Guess)
{
// incriment the turn number
MyCurrentTry++;
// setup a return variable
FBullCowCount BullCowCount;
// loop through all letters in the guess
int32 HiddenWordLength = MyHiddenWord.length();
for (int32 i = 0; i < Guess.length(); i++) {
// compare letters against the hidden word
for (int32 j = 0; j < HiddenWordLength; j++) {
// if they match then
if (Guess[j] == MyHiddenWord[i]) {
if (i == j) { // if they're in the same place
BullCowCount.Bulls++; // incriment bulls
}
else {
BullCowCount.Cows++; // must be a cow
}
}
}
}
return BullCowCount;
}
When debugging it took me to the line referred to in xstring it gives the following error:
Unhandled exception at 0x1005E5F6 (ucrtbased.dll) in BullCowGame.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
for the code:
reference operator[](const size_type _Off)
{ // subscript mutable sequence
auto& _My_data = this->_Get_data();
_IDL_VERIFY(_Off <= _My_data._Mysize, "string subscript out of range");
return (_My_data._Myptr()[_Off]);
}
There appears to be a breakpoints triggered by something I did, but the code reflects the code in the tutorial and the tutorial code compiles and runs correctly.
Does anyone know how to deal with this? I'm coming up empty on searches.
This looks very suspicious:
for (int32 i = 0; i < Guess.length(); i++) {
// compare letters against the hidden word
for (int32 j = 0; j < HiddenWordLength; j++) {
...
Notice, i is bounded by guess's length, and j is bounded by HiddenWord's length.
Note you mixed up your index variables here:
// if they match then
if (Guess[j] == MyHiddenWord[i]) {
Also, you should have been looking at this line anyway, since the exception was in operator[], and this is the only place in the code you posted that uses the operator in question... :)