I was playing around with C++'s std::string
class, and for fun, I declared a string and tried to modify out-of-bounds characters:
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string str = "Hello World!";
str[5] = 20;
str[20] = 10;
str[200] = 4;
cout << str << endl;
return 0;
}
To my surprise, nothing happened during the program's execution at all (except for str[5] = 20
). I expected the program to crash with a Segmentation Fault, and I'm not quite sure why this doesn't happen. Is this a side effect of "undefined behavior", or is something else at work here?
EDIT:
I even tried adding
cout << str[-1] << endl;
cout << str[200] << endl;
And no runtime errors occurred; it just printed a blank string for both of those lines.