Out of bound char reference

Just experimenting with the code where it loops through the guess and the hidden word to determine if the guess is correct.

This code obviously gives an error when the guess is shorter than the hidden word because of the out of bound reference, but I know we don’t bother fixing that since we only pass it valid guesses.

The part that is confusing me is that it seems to error when I expect it to, except for when I pass in a guess that is 1 character shorter than the hidden word.

I fully expect the out of bounds to happen, but the code seems happy enough to run without any issues. Am I missing something obvious or is this something that c++ just does. I read something about undocumented behavior, could this be an example of that?

Here is the code I’m referring to:

	int32 WordLength = MyHiddenWord.length(); // assuming same length as guess

	// loop through all letters in the hidden word
	for (int32 MHWChar = 0; MHWChar < WordLength; MHWChar++) {
		// compare letters against the guess
		for (int32 GChar = 0; GChar < WordLength; GChar++) {
			// if they match then
			if (Guess[GChar] == MyHiddenWord[MHWChar]) {
				if (MHWChar == GChar) { // if they're in the same place
					BullCowCount.Bulls++; // incriment bulls
				}
				else {
					BullCowCount.Cows++; // must be a cow
				}
			}
		}
	}

Take a look at how and when this function would be called, would it happen if the length isn’t the same?

Hi Dan,

Thanks for the quick response!

I guess I’m just being picky about this one. I know that this function would never get called if the guess and the hidden word are not the same length. What is bugging me, is that the code seems happy to run when I know I making an out of bounds reference on the string.

I commented out the valid guess check and put in a guess that is 1 letter short of the hidden word, lets say “plane” for the guess and “planet” for the hidden word, but when GChar would be 5, (i.e. the last iteration of the second for loop) I am technically calling for the 6th character of a 5 character string, so I would expect to get an error, but I don’t.

I guess what I’m looking to understand is less about the intended function of the game and more about the behavior of the language.

Thanks,
Chris

Oh okay I was under the impression you didn’t comment out the error checking; but a word that is 1 letter short wouldn’t throw an exception since Guess[N] would be \0 and still within bounds.

Ah, that’s exactly what I was looking for.

Thanks a bunch Dan!

Note that this might not always be the case, and might throw an exception on older/different implentations(basically pre-C++11).

Thanks for the note. I suppose good practice would be to never try to access at an out of bound index, but I’m glad I understand this now.

Privacy & Terms