Main Content

ISO/IEC TS 17961 [ptrcomp]

Accessing an object through a pointer to an incompatible type

Description

Rule Definition

Accessing an object through a pointer to an incompatible type.1

Polyspace Implementation

This checker checks for Conversion between pointers to different objects.

Examples

expand all

Issue

The issue occurs when a cast is performed between a pointer to object type and a pointer to a different object type.

Risk

If a pointer to an object is cast into a pointer to a different object, the resulting pointer can be incorrectly aligned. The incorrect alignment causes undefined behavior.

Even if the conversion produces a pointer that is correctly aligned, the behavior can be undefined if the pointer is used to access an object.

Exception: You can convert a pointer to object type into a pointer to one of the following types:

  • char

  • signed char

  • unsigned char

Example - Noncompliant: Cast to Pointer Pointing to Object of Wider Type
signed   char *p1;
unsigned int *p2;

void foo(void){ 
  p2 = ( unsigned int * ) p1;     /* Non-compliant */				
}

In this example, p1 can point to a signed char object. However, p1 is cast to a pointer that points to an object of wider type, unsigned int.

Example - Noncompliant: Cast to Pointer Pointing to Object of Narrower Type
extern unsigned int read_value ( void );
extern void display ( unsigned int n );

void foo ( void ){
  unsigned int u = read_value ( );
  unsigned short *hi_p = ( unsigned short * ) &u;    /* Non-compliant  */	
  *hi_p = 0;                                         
  display ( u );                                     
}

In this example, u is an unsigned int variable. &u is cast to a pointer that points to an object of narrower type, unsigned short.

On a big-endian machine, the statement *hi_p = 0 attempts to clear the high bits of the memory location that &u points to. But, from the result of display(u), you might find that the high bits have not been cleared.

Example - Compliant: Cast Adding a Type Qualifier
const short *p;
const volatile short *q;
void foo (void){
  q = ( const volatile short * ) p;  /* Compliant */								
}

In this example, both p and q can point to short objects. The cast between them adds a volatile qualifier only and is therefore compliant.

Check Information

Decidability: Undecidable

Version History

Introduced in R2019a

expand all


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.