Main Content

ISO/IEC TS 17961 [ptrobj]

Subtracting or comparing two pointers that do not refer to the same array

Description

Rule Definition

Subtracting or comparing two pointers that do not refer to the same array.1

Polyspace Implementation

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

Examples

expand all

Issue

Subtraction or comparison between pointers to different arrays 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; 
    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

Decidability: Undecidable

Version History

Introduced in R2019a


1 Extracts from the standard "ISO/IEC TS 17961 Technical Specification - 2013-11-15" are reproduced with the agreement of AFNOR. Only the original and complete text of the standard, as published by AFNOR Editions - accessible via the website www.boutique.afnor.org - has normative value.