Versions Compared

Key

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

Associative containers place a strict weak ordering requirement on their key comparison predicates [ISO/IEC 14882-2014]. A strict weak ordering has the following properties:

  • For all xx < x == false (irreflexivity)
  • For all x, yx < y != y < x (asymmetry)
  • For all x, yzx < y && y < z == x < z (transitivity)

Providing an invalid ordering rule predicate for an associative container, or as a comparison criterion with the sorting algorithms, can result in erratic behavior or infinite loops . (See Meyers01 §21 for examples.)

...

[Meyers 01]. When an ordering predicate is required for an associative container or a generic STL algorithm, the predicate must meet the requirements for inducing a strict weak ordering.

Noncompliant Code Example

In this non-compliant example, the IntSetLE type defines a set with less_equal specified as the ordering rule. Less than or equal is not a valid ordering rule because it violates the requirement to provide a "strict weak ordering" over the objects compared. In particular, this ordering rule noncompliant code example, the std::set object is created with a comparator that does not adhere to the strict weak ordering requirement. Specifically, it fails to return false for equal equivalent values. As a result, the iterator pair returned by the equal_range() method is inverted and the subsequent loop fails to terminate.behavior of iterating over the results from std::set::equal_range results in unspecified behavior:

Code Block
bgColor#FFcccc
langcpp
typedef set<int, less_equal<int > > IntSetLE;

IntSetLE::const_iterator sleIter;
IntSetLE sle;

sle.insert(5);
sle.insert(10);
sle.insert(20);

pair<IntSetLE::const_iterator, IntSetLE::const_iterator> psle;

psle = sle#include <functional>
#include <iostream>
#include <set>

void f() {
  std::set<int, std::less_equal<int>> S{5, 10, 20};  
  for (auto R = S.equal_range(10);

for (sleIter = psle R.first; sleIter != psleR.second; ++sleIterR.first) {
    std::cout << "Set contains: " << *sleIter*R.first << std::endl;
  }
}

Compliant Solution

Provide an ordering rule that defines a strict weak ordering.This compliant solution uses the default comparator with std::set instead of providing an invalid one:

Code Block
bgColor#ccccff
langcpp
typedef set<int, less<int> > IntSetLess;

IntSetLess::const_iterator islIter;
IntSetLess isl;

isl.insert(5);
isl.insert(10);
isl.insert(20);

pair<IntSetLess::const_iterator, IntSetLess::const_iterator> pisl;

pisl = isl#include <iostream>
#include <set>

void f() {
  std::set<int> S{5, 10, 20};  
  for (auto R = S.equal_range(10);

for (islIter = pisl R.first; islIter != pislR.second; ++islIterR.first) {
  cout << "Set contains: " std::cout << *islIterR.first << std::endl;
  }
}

...

Noncompliant Code Example

In this non-compliant noncompliant code example, the IntPtrSet type defines a set of int pointers using the default comparison operator as the ordering rule. Unfortunately the default comparison operator will compare the pointer address values, not the values of the ints referenced by the pointers. As a result, the integers will be ordered consistently, but their order will appear to be scrambledobjects stored in the std::set have an overloaded operator< implementation, allowing the objects to be compared with std::less. However, the comparison operation does not provide a strict weak ordering. Specifically, the values 1, N and 1, M can result in a situation where comp(x, y) == comp(y, x), failing the asymmetry requirements.

Code Block
bgColor#FFcccc
langcpp
typedef set<int*> IntPtrSet;

IntPtrSet::const_iterator sIter;
IntPtrSet s;

int i[3] = {10, 20, 5};
s.insert(&i[2]);
s.insert(&i[1]);
s.insert(&i[0]);

cout << "Set contains ";
for (sIter = s.begin(); sIter != s.end(); ++sIter) cout << **sIter << ' ';
cout << endl;

This code outputs:

Set contains 10 20 5

because the integers are stored in pointer order, which happens to be the order in which they are stored in the array.

Compliant Solution

#include <iostream>
#include <set>

class S {
  int I, J;

public:
  S(int I, int J) : I(I), J(J) {}
  
  friend bool operator<(const S &LHS, const S &RHS) {
    return LHS.I < RHS.I && LHS.J < RHS.J;
  }
  
  friend std::ostream &operator<<(std::ostream &OS, const S& O) {
    OS << "I: " << O.I << ", J: " << O.J;
    return OS;
  }
};

void f() {
  std::set<S> T{S(1, 1), S(1, 2), S(2, 1)};
  for (auto V : T) {
    std::cout << V << std::endl;
  }
}

Compliant Solution

This compliant solution uses std::tie() to properly implement the strict weak ordering operator< predicateTo store pointers in a proper order, you should use the DereferenceLess template, as described in
[Meyers 01] Item 20:

Code Block
bgColor#ccccff
langcpp
struct DereferenceLess#include <iostream>
#include <set>
#include <tuple>
 
class S {
  template <typename PtrType>int I, J;
 
public:
  S(int I, int J) : I(I), J(J) {}
  
  friend bool operator()(PtrType pl1, PtrType pl2) const {
    return *pl1 < *pl2operator<(const S &LHS, const S &RHS) {
    return std::tie(LHS.I, LHS.J) < std::tie(RHS.I, RHS.J);
  }
  
  friend std::ostream &operator<<(std::ostream &OS, const S& O) {
    OS << "I: " << O.I << ", J: " << O.J;
    return OS;
  }
};

Now if we use this template when declaring the set:

Code Block
bgColor#ccccff
langcpp
typedef set<int*, DereferenceLess> IntPtrSet;

the rest of the program behaves as we expect:

...


void f() {
  std::set<S> T{S(1, 1), S(1, 2), S(2, 1)};  
  for (auto V : T) {
    std::cout << V << std::endl;
  }
}

Risk Assessment

Using an invalid ordering rule can lead to erratic behavior or infinite loops.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ARR40CTR40-CPP

lowLow

probableProbable

highHigh

P2

L3

Other Languages

...

Automated Detection

Tool

Version

Checker

Description

    

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

Bibliography

[ISO/IEC 14882-2014]

23.2.4, "Associative Containers"

[Meyers 01]Item 21: Always have comparison functions return false for equal values

...

[Sutter 05]Item 83: Use a checked STL implementation

 .
[ISO/IEC 14882-2003] Section 24: Iterators Library.

CTR39-CPP. Do not use pointer arithmetic on polymorphic objects      06006. Containers (CTR)      CTR41-CPP. A container's allocator should never have a data field that is not staticImage Added