Use of Pointer Subtraction to Determine Size
The application subtracts one pointer from another in order to determine size, but this calculation can be incorrect if the pointers do not exist in the same memory chunk.
The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.
Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.
The following example contains the method size that is used to determine the number of nodes in a linked list. The method is passed a pointer to the head of the linked list.
However, the method creates a pointer that points to the end of the list and uses pointer subtraction to determine the number of nodes in the list by subtracting the tail pointer from the head pointer. There no guarantee that the pointers exist in the same memory area, therefore using pointer subtraction in this way could return incorrect results and allow other unintended behavior. In this example a counter should be used to determine the number of nodes in the list, as shown in the following code.
Weaknesses in this category are related to the rules and recommendations in the Arrays (ARR) section of the SEI CERT C Coding Standard.
This category identifies Software Fault Patterns (SFPs) within the Glitch in Computation cluster (SFP1).
Weaknesses in this category are related to rules in the Arrays and the STL (ARR) section of the CERT C++ Secure Coding Standard. Since not all rules map to specific we...
This view (slice) covers all the elements in CWE.
This view contains a selection of weaknesses that represent the variety of weaknesses that are captured in CWE, at a level of abstraction that is likely to be useful t...
This view (slice) lists weaknesses that can be introduced during implementation.