Versions Compared

Key

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

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 (C11, Section 6.5.6 [ISO/IEC 9899:2011]); the result is the difference of the subscripts of the two array elements. Otherwise, the operation results in undefined behavior . (See undefined behavior 48  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 undefined behavior 48 and undefined behavior 53 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, or points one past the last element of an array object or function.

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V

438 S

Fully implemented.

PRQA QA-C
Include Page
PRQA_V
PRQA_V

0487

2771

 

Fully implemented

Related Vulnerabilities

...

MITRE CWE: CWE-469, "Use of pointer subtraction to determine size"

Bibliography

[Banahan 2003] Section 5.3, "Pointers," and Section 5.7, "Expressions involving pointers"

...