...
References, pointers, and iterators referring to the elements of a
basic_string
sequence may be invalidated by the following uses of thatbasic_string
object:
- as As an argument to any standard library function taking a reference to non-const
basic_string
as an argument.- Calling non-const member functions, except
operator[]
,at
,front
,back
,begin
,rbegin
,end
, andrend
.
Examples of standard library functions taking a reference to non-const
std::basic_string
are : std::swap()
, ::operator>>(basic_istream &, string &)
, and std::getline()
.
Do not use a an invalidated reference, pointer, or iterator that has been invalidated, as that because doing so results in undefined behavior. This rule is a specific instance of CTR51-CPP. Use valid references, pointers, and iterators to reference elements of a container.
...
This noncompliant code example copies input
into a std::string
, replacing 'semicolon (;' ) characters with spaces. This example is noncompliant because the iterator loc
is invalidated after the first call to insert()
. The behavior of subsequent calls to insert()
is undefined.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <string> void f(const std::string &input) { std::string email; std::string::iterator loc = email.begin(); // copyCopy input into email converting ";" to " " for (auto I = input.begin(), E = input.end(); I != E; ++I, ++loc) { email.insert(loc, *I != ';' ? *I : ' '); } } |
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <string> void f(const std::string &input) { std::string email; std::string::iterator loc = email.begin(); // copyCopy input into email converting ";" to " " for (auto I = input.begin(), E = input.end(); I != E; ++I, ++loc) { loc = email.insert(loc, *I != ';' ? *I : ' '); } } |
...
Using an invalid reference, pointer, or iterator to a string object could allow an attacker to run arbitrary code.
...
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ Coding Standard | CTR51-CPP. Use valid references, pointers, and iterators to reference elements of a container |
...