Use of Pointer Subtraction to Determine Size

The product 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.


Demonstrations

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.

Example One

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.

struct node {
  int data;
  struct node* next;
};

// Returns the number of nodes in a linked list from

// the given pointer to the head of the list.
int size(struct node* head) {
  struct node* current = head;
  struct node* tail;
  while (current != NULL) {
    tail = current;
    current = current->next;
  }
  return tail - head;
}

// other methods for manipulating the 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.

...

int size(struct node* head) {
  struct node* current = head;
  int count = 0;
  while (current != NULL) {
    count++;
    current = current->next;
  }
  return count;
}

See Also

Comprehensive Categorization: Incorrect Calculation

Weaknesses in this category are related to incorrect calculation.

SEI CERT C Coding Standard - Guidelines 06. Arrays (ARR)

Weaknesses in this category are related to the rules and recommendations in the Arrays (ARR) section of the SEI CERT C Coding Standard.

SFP Secondary Cluster: Faulty Pointer Use

This category identifies Software Fault Patterns (SFPs) within the Faulty Pointer Use cluster (SFP7).

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

CWE Cross-section

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...

Weaknesses Introduced During Implementation

This view (slice) lists weaknesses that can be introduced during implementation.


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.