...
Code Block |
---|
|
#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 |
---|
|
#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 |
---|
|
#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.
...