Jonathan. Jonathan. - 3 months ago 6
C++ Question

Behaviour of attempting to access a character at index -1 for std::string?

Is there any guaranteed behaviour for attempting to access a character at

-1
in a std::string?

Eg if I do:

for (int i = 0; i < str.size(); i++) {
if (str[i-1] == 'a' && str[i+1] == 'c') {
//etc
}
}


Then on the first iteration it will do
str[-1]
, what does the standard say will happen? I know it says in C++11 that str[str.size()] will return the null character, but sites like cppreference and cplusplus don't say anything about other out of bounds accesses.

(if I run the code above, then nothing bad happens, but I want to make sure that this is standard)

Answer

Is there any guaranteed behaviour for access the character at -1 in a std::string?

Formally, it depends. In practice, it is undefined behaviour, so there are no guarantees.

The parameter of operator[] is unsigned, so -1 is the maximum value that type can hold (std::numeric_limits<std::string::size_type>::max()). Since that is also the maximum value std::string::size() can hold, it could be well defined only in the (extremely improbable) case that the string has the largest size allowed, in which case a reference to the null terminator is returned.

Comments