Subtraction or comparison between pointers to different arrays
Subtraction or comparison between pointers causes undefined behavior
Description
This defect occurs when you subtract or compare pointers that are null or that point
to elements in different arrays. The relational operators for the comparison are
>
, <
, >=
, and
<=
.
Risk
When you subtract two pointers to elements in the same array, the result is the difference between the subscripts of the two array elements. Similarly, when you compare two pointers to array elements, the result is the positions of the pointers relative to each other. If the pointers are null or point to different arrays, a subtraction or comparison operation is undefined. If you use the subtraction result as a buffer index, it can cause a buffer overflow.
Fix
Before you subtract or use relational operators to compare pointers to array elements, check that they are non-null and that they point to the same array.
Examples
Result Information
Group: Static memory |
Language: C | C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax:
PTR_TO_DIFF_ARRAY
|
Impact: High |
Version History
Introduced in R2017bSee Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)