A reference, pointer or iterator into a vector or string is used after the container may have reallocated
What it finds
int &first = v[0]; v.push_back(x); use(first);: a reference, pointer or iterator to an element of a std::vector or std::string is invalidated when the container grows past its capacity, is cleared or is resized, since the elements may move to new storage. Reading through it afterwards is undefined.
``cpp std::vector<Item> items = load(); Item &last = items.back(); items.push_back(Item{}); // may move every element last.count++; // writes to freed memory ``
The rule looks at one block at a time: a reference or pointer declared from an element (v[i], v.at(i), v.front(), v.back(), &v[i], v.data()) or an iterator from v.begin() or v.end(), then a statement of the same block that calls push_back, emplace_back, insert, emplace, resize, reserve, assign, clear or shrink_to_fit on the container, then a use of the variable later in the block. The container must be a local or parameter declared in the file as a std::vector or std::string object. A container on which reserve is called before the reference is taken is left alone, since its growth may stay within the capacity.
From the rule's source, element_reference_after_growth.rs.
Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/cpp:element-reference-after-growth" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/cpp:element-reference-after-growth] reason="..."tx0 explain tx0/cpp:element-reference-after-growth shows the same in the terminal. Found a false positive? Report it.