| Warning | ||
|---|---|---|
| ||
This is new rule and not yet ready for review. |
When two pointers are subtracted, both must point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. 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 can tell you the relative positions of the pointers in term of each other. Subtracting or comparing pointers the that do not refer to the same array will lead to can result in undefined behavior.
Non-Compliant Code Example
In this non-compliant code example pointer subtraction is used to determine how many free elements are left in the nums array.
| Code Block | ||
|---|---|---|
| ||
int nums[SIZE];
char *strings[SIZE];
int next_num_ptr = nums;
int free_bytes;
/* perform operations on next_num_ptr as array fills */
free_bytes = strings - next_num_ptr;
|
In this non-compliant code example pointer subtraction is used to determine how many free elements are left in the nums array. The first incorrect assumption is that nums and strings arrays will be next to each other in memory. The second is that free_bytes will be the number of bytes available. The subtraction will return the number of elements between next_num_ptr and strings.
Compliant Solution
In this compliant solution, the number of free elements is kept as a counter and adjusted on every array operation. It is also calculated in terms of free elements instead if bytes. This prevents further mathematical errors.
| Code Block | ||
|---|---|---|
| ||
ntint nums[SIZE]; char *strings[SIZE]; int next_num_ptr = nums; int free_elements = SIZE; /* perform operations on next_num_ptr as array fills decrement free_elements as it fills */ |
...
Risk Assessment
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
ARR36-C | 2 (medium) | 2 (probable) | 2 (medium) | P6 | L2 |
...