Main Content

MISRA C:2012 Rule 11.3

A conversion shall not be performed between a pointer to object type and a pointer to a different object type

Description

Rule Definition

A conversion shall not be performed between a pointer to object type and a pointer to a different object type.

Rationale

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.

As an exception MISRA C:2012 standard permits converting a pointer to a non-atomic qualified object type into a pointer to one of the following types:

  • char

  • signed char

  • unsigned char

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

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.

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.

typedef struct {
	int iNum1;
}A;

typedef struct {
	int iNum2;
}B;

void bar(A*);

void foo() {
	B wrappedNum2;
	bar(&wrappedNum2); /* Noncompliant*/

}

In this example, the B type struct object wrappedNum2 is implicitly cast into an A type struct object in the call to bar. Polyspace® flags the implicit casting.

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

Group: Pointer Type Conversions
Category: Required
AGC Category: Required

Version History

Introduced in R2014b

expand all