Let's say I'm iterating through a string, char by char, doing some operation with them, and my algorithm accidentally iterates once more than needed, that is: it evaluates the char positioned on str[str.length()]
On the visual part nothing changes. So what would be the dangers of doing that? What is exactly wrong with doing it?
Thanks.
Thanks :)
But what could happen? I mean, is there a case where this undefined behavior could damage the execution of the program?
I know it's wrong reading a char that doesn't exist. I'm just trying to make a point with a buddy who says it's no big deal because nothing bad happens anyway, hehe.
If you have allocated extra spaces, and initialised them to '\0' for the string, nothing critical happens - you'll just get one weird char.
If you have just enough space for the string and ending '\0', you might have massed up with the terminating of the string - by counting length or printing it, your program may crash, or just printing out some weird characters, or, the worst case, your program would execute some unexpected instructions.
str[str.length()] is well-defined as long as we do not modify the referenced value.
note: str[str.length()] yields a reference to a null character (a char with a value of zero)
C++11 requires that the complexity of invoking the member function c_str() is constant. The only practical way to meet this complexity requirement would be by leaving space to store an extra null character at the end, immediately after the actual last character in the string.
Returns: *(begin() + pos) if pos < size().
Otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified.