Main Content

CWE Rule 469

Use of Pointer Subtraction to Determine Size

Since R2023a

Description

Rule Description

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.

Polyspace Implementation

The rule checker checks for Subtraction or comparison between pointers to different arrays.

Examples

expand all

Issue

This issue occurs when you subtract or compare pointers that are null or that point to elements in different arrays. The relational operators for the comparison are >, <, >=, and <=.

Risk

When you subtract two pointers to elements in the same array, the result is the difference between the subscripts of the two array elements. Similarly, when you compare two pointers to array elements, the result is the positions of the pointers relative to each other. If the pointers are null or point to different arrays, a subtraction or comparison operation is undefined. If you use the subtraction result as a buffer index, it can cause a buffer overflow.

Fix

Before you subtract or use relational operators to compare pointers to array elements, check that they are non-null and that they point to the same array.

Example — Subtraction Between Pointers to Elements in Different Arrays
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE20 20

size_t func(void)
{
    int nums[SIZE20];
    int end;
    int *next_num_ptr = nums;
    size_t free_elements;
	/* Increment next_num_ptr as array fills */
	
	/* Subtraction operation is undefined unless array nums 
	is adjacent to variable end in memory. */
    free_elements = &end - next_num_ptr;  //Noncompliant
    return free_elements;
}
    
      

In this example, the array nums is incrementally filled. Pointer subtraction is then used to determine how many free elements remain. Unless end points to a memory location one past the last element of nums, the subtraction operation is undefined.

Correction — Subtract Pointers to the Same Array

Subtract the pointer to the last element that was filled from the pointer to the last element in the array.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE20 20

size_t func(void)
{
    int nums[SIZE20];
    int *next_num_ptr = nums;
    size_t free_elements;
	/* Increment next_num_ptr as array fills */
	
	/* Subtraction operation involves pointers to the same array. */
    free_elements = &(nums[SIZE20 - 1]) - next_num_ptr;  
	
    return free_elements + 1;
}
     

Check Information

Category: Pointer Issues

Version History

Introduced in R2023a