CWE-469: Use of Pointer Subtraction to Determine Size

http://cwe.mitre.org/data/definitions/469.html


Example 1

The following example contains the method size that is used todetermine the number of nodes in a linked list. The method is passed apointer to the head of the linked list.

(Bad Code)
Example Languages: C and C++ 
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 thelist and uses pointer subtraction to determine the number of nodes inthe list by subtracting the tail pointer from the head pointer. There noguarantee that the pointers exist in the same memory area, thereforeusing pointer subtraction in this way could return incorrect results andallow other unintended behavior. In this example a counter should beused to determine the number of nodes in the list, as shown in thefollowing code.

(Good Code)
Example Languages: C and C++ 

...

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章