...
The behavior of this non-compliant example is undefined because the index i
used to reference bs
may be outside the range of bs
, causing a write-out-of-bounds error.
Code Block |
---|
|
string bs("01234567");
size_t i = f();
bs[i] = '\0';
|
...
Wiki Markup |
---|
This compliant solution uses the {{basic_string at()}} method, which behaves in a similar fashion to the index {{operator\[\]}} but throws an {{out_of_range}} exception if {{pos >= size()}}. |
Code Block |
---|
|
string bs("01234567");
try {
size_t i = f();
bs.at(i) = '\0';
}
catch (...) {
cerr << "Index out of range" << endl;
}
|
...
The behavior of this non-compliant example is undefined because the size()
of bs
is 8 but the index used to reference bs
ranges from 0 through 99.
Code Block |
---|
|
string bs("01234567");
for (int i=0; i < 100; i++) {
bs[i] = '\0';
}
|
...
Use the fill algorithm to assign the value '\0'
to evey element in the specified range:
Code Block |
---|
|
const size_t max_fill = 100;
std::string bs("01234567");
fill(bs.begin(), bs.begin()+std::min(max_fill, bs.length()), '\0' );
|
...