Why is it unsafe to read inexistent string characters?

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.
It is out of bounds and worse undefined behavior. You cannot predict what happens.
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.
That depends.

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.

So do it carefully...

it evaluates the char positioned on str[str.length()]


That's a segmentation fault.

I am fairly sure that an std::end function won't behave like that.

If you are processing a whole container, use a range based for loop, avoid the problem altogether.

http://en.cppreference.com/w/cpp/iterator/end
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.

As a consequence, the IS specifies:
1
2
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);

Requires: pos <= size().

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.

Throws: Nothing.

Complexity: constant time.
Topic archived. No new replies allowed.