Versions Compared

Key

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

The std::string index operators const_reference operator[](size_type) const and reference operator[](size_type) return the character stored at the specified position, pos. When pos >= size(), a reference to an object of type charT with value charT() is returned. The index operators are unchecked (no exceptions are thrown for range errors), and attempting to modify the resulting out-of-range object results in undefined behavior.

Similarly, the std::string::back() and std::string::front() functions are unchecked as they are defined to call through to the appropriate operator[]() overload without throwing.

Do not pass an out-of-range value as an argument to std::string::opperator[](). Similarly, do not call std::string::back(), or std::string::front() on an empty string. This rule is a specific instance of CTR50-CPP. Guarantee that container indices and iterators are within the valid range.

...

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
bgColor#FFcccc
langcpp
#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
bgColor#ccccff
langcpp
#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 noncompliant code example attempts to replace the initial character in the string with a capitalized equivalent. However, if the given string is empty, the behavior is undefined.

Code Block
bgColor#FFcccc
langcpp
#include <string>
#include <locale>

void capitalize(std::string &S) {
  std::locale L;
  S.front() = std::use_facet<std::ctype<char>>(L).toupper(S.front());
}

...

In this compliant solution, the call to std::string::front() is made only made if the string is not empty:

...

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...