Versions Compared

Key

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

According to section 6.5.6 of C99, when two pointers are subtracted, both must point to elements of the same array object or to one past the last element of the array object; the result is the difference of the subscripts of the two array elements. Otherwise, the operation results in undefined behavior . (see See undefined behavior 45 of Appendix J.) . This restriction exists because pointer subtraction in C produces the number of objects between the two pointers, not the number of bytes.

Similarly, comparing pointers using the relational operators <, <=, >=, and > gives the positions of the pointers relative to each other. Subtracting or comparing pointers that do not refer to the same array results in undefined behavior. (see See undefined behavior 46 of Appendix J.) .

Comparing pointers using the equality operators == and != has well-defined semantics regardless of whether or not either of the pointers is null, points into the same object, one past the last element of an array object, or function.

It is acceptable to subtract or compare two member pointers within a single struct object, suitably cast , because any object can be treated as an array of unsigned char. However, when doing so remember to account for the effects of alignment and padding on the structure.

...

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

Other Languages

Related Guidelines

This rule appears in the C++ Secure Coding Standard as : ARR36-CPP. Do not subtract or compare two pointers or iterators that do not refer to the same array or container.

Bibliography

Wiki Markup
\[[Banahan 032003|AA. Bibliography#Banahan 03]\] [Section 5.3, "Pointers,"|http://publications.gbdirect.co.uk/c_book/chapter5/pointers.html] and [Section 5.7, "Expressions involving pointers"|http://publications.gbdirect.co.uk/c_book/chapter5/pointer_expressions.html]
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.5.6, "Additive operators"
\[[MITRE 07207|AA. Bibliography#MITRE 07]\] [CWE ID 469|http://cwe.mitre.org/data/definitions/469.html], "Use of Pointer Subtraction to Determine Size"

...