How is access of an index more than string's size in c++ allowed?

Viewed 78
#include <iostream>
using namespace std;

int main() {
    // your code goes here
    string g = "12345";
    cout << g[10] << endl; // Prints an empty character
    
    return 0;
}

Reference: https://ideone.com/rpCWm2

This surprisingly works and doesn't throw an error! Can somebody explain how this is happening? Thank you!

1 Answers
std::string g = "12345";
std::cout << g[10] << std::endl;

Your access is out-of-bounds, which makes it an undefined behaviour. Undefined behaviour can do anything, from running normally to crashing the program.

If you use the at() function instead(which does bound-checking), you will see that this will throw an std::out_of_range exception.

std::string g = "12345";
std::cout << g.at(10) << std::endl;
Related