Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

References, pointers, and iterators referring to the elements of a basic_string sequence may be invalidated by the following uses of that basic_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, and rend.

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
bgColor#FFcccc
langcpp
#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
bgColor#ccccff
langcpp
#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

...