'C++ How am I able to access this strings s.size index?

void run_case() {
    int N, K;
    cin >> N >> K;
    string S;
    cin >> S;
    cout << S[6] << '\n';
    int goodness = 0;
    for (int i = 0; i <= N/2-1; i++)
    {
        cout << i << ' ' << S[i] << ' ' << N - i << ' ' << S[N-i] << '\n';
        if (S[i] != S[N - i]) goodness++;
    }
    cout << goodness << '\n';
}

So I entered this input:

1

6 1

CABABC

S's size is 6 why am I able to print it out and do all this stuff when S[6] doesn't exist..? S[5] is the last char can anyone explain why this is happening? I mean I know that C style strings have an extra char to signal that it's over but what's going on here?

c++


Solution 1:[1]

std::string::operator[ s.size() ] has changed in C++11. Before:

  1. If pos == size(), the behavior is undefined.
  2. If pos == size(), a reference to the character with value CharT() (the null character) is returned.

Where 1) refers to the non-const overload and 2) to the const overload. Since C++11:

If pos == size(), a reference to the character with value CharT() (the null character) is returned. For the first (non-const) version, the behavior is undefined if this character is modified to any value other than CharT().

When the size of the string is 6 then S[6] is completely fine. You just are not allowed to assign anything to it other than \0.


However, as mentioned in a comment, when your first input is 1 then S == "1" and accessing any index other than 0 or 1 is out-of-bounds. Attempting to access an out-of-bounds index is undefined behavior. Anything can happen. In the worst case the code might appear to work fine. It is important to understand that undefined behavior is typically not caught by compiler errors (though often compilers can warn about it).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1