...
In this noncompliant code example, the value returned by the call to get_index()
may be greater than the number of elements stored in the string, resulting in undefined behavior:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <string> extern std::size_t get_index(); void f() { std::string s("01234567"); s[get_index()] = '1'; } |
...
This compliant solution uses the std::basic_string::at()
function, which behaves in a similar fashion to the index operator[]
but throws a std::out_of_range
exception if pos >= size()
:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdexcept> #include <string> extern std::size_t get_index(); void f() { std::string s("01234567"); try { s.at(get_index()) = '1'; } catch (std::out_of_range &) { // Handle error } } |
...
This compliant solution checks that the value returned by get_index()
is within a valid range before calling operator[]()
:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <string> extern std::size_t get_index(); void f() { std::string s("01234567"); std::size_t i = get_index(); if (i < s.length()) { s[i] = '1'; } else { // Handle error } } |
...
In this compliant solution, the call to std::string::front()
is made only if the string is not empty:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <string> #include <locale> void capitalize(std::string &s) { if (s.empty()) { return; } std::locale loc; s.front() = std::use_facet<std::ctype<char>>(loc).toupper(s.front()); } |
...
Unchecked element access can lead to out-of-bounds bound reads 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.
...