The index operators:
Code Block |
---|
const_reference operator[](size_type pos) const; |
...
reference operator[](size_type pos); |
return the character stored at the specified position if
1 Returns: If pos < size
(), returns data()
pos. Otherwise, if If pos == size()
, the const
version returns charT()the terminating null character type value. Otherwise, the behavior is undefined.
const_reference at(size_type pos) const;
reference at(size_type pos);
2 Requires: pos < size()
3 Throws:
In any case, the behavior of the index operators is unchecked (no exceptiosn are thrown).
Non-Compliant Example
The behavior of this non-compliant example is undefined becuase 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] = 'X';
}
|
This program does not typically raise an exception and is likely to crash.
Compliant Solution
The following compliant solution uses the basic_string at()
method which behaves in a similar fashion to the index operator[]
but throws an out_of_range
if pos >= size()
. 4 Returns: operator[](pos)
Code Block |
---|
string bs("01234567");
try {
for (int i = 0; i < 100; i++) {
bs.at(i) = '\0';
}
}
catch (...) {
cerr << "Index out of range" << endl;
}
|
Consequences
Unchecked element access can lead to out-of-bounds read and writes and write-anywhere exploits. These exploits can in turn lead to the execution of arbitrary code with the permissions of the vulnerable process.
References
Section 21.3.4 basic_string element access