std::string no out_of_range error?

I am learning C++ with the book "Programming, principles and practices using c++" from Bjarne Stroustrup. I am busy with some exercises to learn about compiler/linker and runtime errors in chapter 5.
Here the code fragment:
 
 string s = "Success!\n"; for (int i=0; i<10; ++i) cout << s[i];


The size of string s = 9. The For loop will executed 10 times, so why there's no error (like at a out_of_range error at a vector).
Last edited on
First of all there is no range checking on operator[]. You want to use .at() for that. With operator[] you would get at worst crash if you try to touch unallocated memory.

Even if we assume worst, your example is correct: in C++11 accessing s[s.size()] will return you null terminator: strings are null-terminate internally to ensure fast c_str and compatibility with C functions expecting c-string.
Ok, thank you for your answer.
When I try to access s[s.size()+1] and write a character to this position, no error occurs.
cout << s;
Only the original string will be printed ( I think because of the null-terminate) , but when
cout << s[s.size() + 1];
the character will be printed; Could this be a problem, maybe I touch other allocated memory?
When I try to access s[s.size()+1] and write a character to this position, no error occurs.
I repeat, opearator[] does not check boundaries. It is up to you. If you want to emit an error in this case, use .at().

Could this be a problem, maybe I touch other allocated memory?
Yes. It is a problem. Your program now contains undefined behavior, which means that it can literally do anything. You might break some other object and it will bite you in the back later. Maybe nothing will change. Maybe you just triggered apocalypse.
Yes. It is a problem. Your program now contains undefined behavior, which means that it can literally do anything. You might break some other object and it will bite you in the back later. Maybe nothing will change. Maybe you just triggered apocalypse

Thank you, you have answered my question (this is what I more or less thought) and thank you for a solution for producing an error in the case I exceed the string size.
Topic archived. No new replies allowed.