Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: updated to conform to ARR36-C

...

Similarly, comparing pointers gives using the relational operators <<=>=, and > gives the positions of the pointers relative to each other within the array. Subtracting or comparing pointers that do not refer to the same array can result results in erroneous undefined behavior.

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.

...

Code Block
bgColor#ffcccc
langcpp
int nums[SIZE];
char *strings[SIZE];
int *next_num_ptr = nums;
int free_bytes;

/* increment next_num_ptr as array fills */

free_bytes = strings - (char **)next_num_ptr;

The first incorrect assumption is that nums and strings arrays are necessarily contiguous This program incorrectly assumes that the nums array is adjacent to the end variable in memory. The second is that free_bytes is the number of bytes available. The subtraction returns the number of elements between next_num_ptr and stringsA compiler is permitted to insert padding bits between these two variables, or even reorder them in memory.

Compliant Solution (Arrays)

...

Code Block
bgColor#ccccff
langcpp
vector<int> nums1(10, 0);
vector<int> nums2(10, 0);
vector<int>::iterator i1 = nums1.begin();
vector<int>::iterator i2 = nums1.end();

int distance = i2 - i1;

Exceptions

ARR36-EX1: Comparing two pointers to char within the same object is allowed.

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ARR36-CPP

medium

probable

medium

P8

L2

...