Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
Reallocation can occur when a member function modifies its container. Modifying member functions include {{reserve()}} and {{resize()}}, {{push_back()}}, {{pop_back()}}, {{erase()}}, {{clear()}}, {{insert()}}, and others. In addition, assignment operations and modifying algorithms can also cause reallocation. When a container reallocates its elements, their addresses change. Consequently, the values of existing iterators are invalidated \[[Kalev 99|AA. C++ References#Kalev 99]\]. Using invalid iterators yields undefined results.

Non-Compliant Code Example

In this example, the iterator pos is invalidated after the call to insert, and subsequent loop iterations have undefined behavior.

Code Block
bgColor#FFcccc
double data[5] = { 2.3, 3.7, 1.4, 0.8, 9.6 };

deque<double> d;
deque<double>::iterator pos = d.begin();

for (size_t i = 0; i < 5; ++i) {
  d.insert(pos++, data[i] + 41);
}

Compliant Solution 1

Update pos each time insert is called to keep the iterators valid, and then increment it:

Code Block
bgColor#ccccff
double data[5] = { 2.3, 3.7, 1.4, 0.8, 9.6 };

deque<double> d;
deque<double>::iterator pos = d.begin();

for (size_t i = 0; i < 5; ++i) {
  pos = d.insert(pos, data[i] + 41);
  ++pos;
}

Compliant Solution 2

Use one of the STL algorithms.

Code Block
bgColor#ccccff
double data[5] = { 2.3, 3.7, 1.4, 0.8, 9.6 };
deque<double> d;

transform(data, data+5,
    inserter(d, d.begin()),
    bind2nd(plus<int>(), 41));

Risk Assessment

Using invalid iterators yields undefined results.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

STL30-CPP

3 (high)

2 (probable)

1 (high)

P6

L2

References

Wiki Markup
\[[Meyers 01|AA. C++ References#Meyers 01]\] Item 43: Prefer algorithm calls to hand-written loops.

Wiki Markup
\[[Sutter 04|AA. C++ References#Sutter 04]\] Item 84: Prefer algorithm calls to handwritten loops.

Wiki Markup
\[[Kalev 99|AA. C++ References#Kalev 99]\] ANSI/ISO C+\+ Professional Programmer's Handbook.

Wiki Markup
\[[ISO/IEC 14882-2003|AA. C++ References#ISO/IEC 14882-2003]\] Section 24: Iterators Library.


14. Templates and the STL (TPL)      14. Templates and the STL (TPL)      STL31-CPP. Use Valid Iterator Ranges