Consider the following code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Allie has a cat.";
s[3] = '\0';
cout << s << '\n';
return 0;
}
Is this code valid? Are there any pitfalls that would make it invalid if in addition to what is above we would do some other operations on this string
?
- In C, the
'\0'
character was used as a string terminator.std::string
still seems to follow this tradition. THerefore, it wouldn't be unreasonable to suppose that under certain circumstances a premature'\0'
might break methods likestd::string::size()
. - It wouldn't be unreasonable to suppose that some routines like
cout
might use the underlyingstd::string::c_str()
for their operation, perhaps entering some sort of UB when this null-terminated string is "prematurely terminated".
But suppose that, as on ideone, cout
ing such a std::string
works fine and prints out this:
Alle has a cat.
I’ve compiled and run this program locally and confirmed that it does print out 0x00
in between of l
and e
. Is it valid to print out null characters to the console? Is it valid for text files to contain null characters? gedit
refuses to open the file to which this program's output has been redirected.