Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: xfer string example from CTR51-CPP -> STR52-CPP

...

Code Block
bgColor#ccccff
langcpp
#include <algorithm>
#include <string>
 
void f(const std::string &input) {
  std::string email{input};
  std::replace(email.begin(), email.end(), ';', ' ');
}

Noncompliant Code Example

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 &exampleString) {
  const char *data = exampleString.data();
  // ...
  exampleString.replace(0, 2, "bb");
  // ...
  g(data);
}

Compliant Solution

In this compliant solution, the pointer to exampleString's internal buffer is not generated until after the modifications from replace() have completed:

Code Block
bgColor#ccccff
langcpp
#include <iostream>
#include <string>

extern void g(const char *);

void f(std::string &exampleString) {
  // ...
  exampleString.replace(0, 2, "bb");
  // ...
  g(exampleString.data());
}

Risk Assessment

Using an invalid reference, pointer, or iterator to a string object could allow an attacker to run arbitrary code.

...