First of all, this is NOT homework. I’m using a book I bought for myself to learn the beginning of C++ at home, and it contains an exercise I’m stuck with. It asks me what is wrong with the following code, but I can’t seem to find it. First I thought that it had to do with the fact that there wasn’t a while or for loop and thus it couldn’t repeat itself rendering the ‘i’ useless, but I’m not sure if that’s the true issue here.
for (int i = 0; i <= phrase.size(); ++i)
{
cout << "Character at position " << i << " is: " << phrase[i] << endl;
}
The condition is wrong:
i <= phrase.size()should bei < phrase.size(). Say phrase is a vector of 10 elements.size()will return 10, but in last iteration of the loop,phrase[10]is accessing an element which isn’t there. Dereferencing out of bounds is undefined behaviour, which by C++ standard makes the whole program ill-formed.