Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: only need to hyperlink 1st case of 'undefined behavior'

...

In this compliant solution, pos is assigned a valid iterator on each insertion, preventing undefined preventing undefined behavior:

Code Block
bgColor#ccccff
langcpp
#include <deque>
 
void f(const double *items, std::size_t count) {
  std::deque<double> d;
  auto pos = d.begin();
  for (std::size_t i = 0; i < count; ++i, ++pos) {
    pos = d.insert(pos, items[i] + 41.0);
  }
}

...

In this noncompliant code example, data is invalidated after the call to replace(), and so its use in g() is undefined behavior:

Code Block
bgColor#ffcccc
langcpp
#include <iostream>
#include <string>
 
extern void g(const char *);
 
void f(std::string &example_string) {
  const char *data = example_string.data();
  // ...
  example_string.replace(0, 2, "bb");
  // ...
  g(data);

}

...

Using invalid references, pointers, or iterators to reference elements of a container results in undefined behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CTR51-CPP

High

Probable

High

P6

L2

...