...
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.
Noncompliant Code Example
In this noncompliant 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 are necessarily contingent 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 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 of bytes. This prevents further mathematical errors.
| Code Block | ||
|---|---|---|
| ||
int nums[SIZE]; char *strings[SIZE]; int *next_num_ptr = nums; int free_bytes; /* increment next_num_ptr as array fills */ free_bytes = (nums[SIZE] - next_num_ptr) * sizeof(int); |
Risk Assessment
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
ARR36-CPP | medium | probable | medium | P8 | L2 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as ARR36-C. Do not subtract or compare two pointers that do not refer to the same array.
References
| Wiki Markup |
|---|
\[[Banahan 03|AA. C++ References#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. C++ References#ISO/IEC 9899-1999]\] Section 6.5.6, "Additive operators" \[[MITRE 07|AA. C++ References#MITRE 07]\] [CWE ID 469|http://cwe.mitre.org/data/definitions/469.html], "Use of Pointer Subtraction to Determine Size" |
...