CERT.STR_ACCESS.INVALID
Do not use invalid references, pointers, and iterators to access elements of a basic_string.
The CERT.STR_ACCESS.INVALID checker detects uses of references, pointers, and iterators after an operation invalidates their association with a basic_string. The checker supports intra- and interprocedural cases.
Vulnerability and risk
Operations that modify a basic_string can invalidate references, pointers, and iterators that refer to its elements. Using an invalidated access path results in undefined behavior.
The checker does not report reserve() or shrink_to_fit() calls, because these functions do not always cause reallocation.
Mitigation and prevention
Update an iterator after a mutating operation, or obtain a new pointer or reference only after the operation completes. Avoid using an access path that refers to a string or to its elements after the string has been modified.
Vulnerable code example
#include <string>
void update(std::string& value)
{
const char* data = value.data();
value.replace(0, 2, "bb");
use(data);
}
The pointer in this example may be invalid after replace() modifies the string. Passing it to use() can result in undefined behavior.
Fixed code example
#include <string>
void update(std::string& value)
{
value.replace(0, 2, "bb");
use(value.data());
}
The fixed example obtains the pointer after the string modification.