MISRA.CAST.OBJ_PTR_TO_OBJ_PTR.2012Cast between a pointer to object type and a pointer to a different object type.
MISRA C 2012 Rule 11.3: A cast shall not be performed between a pointer to object type and a pointer to a different object typeC90 [Undefined 20], C99 [Undefined 22, 34] Category: Required Analysis: Decidable, Single Translation Unit Applies to: C90, C99 AmplificationThis rule applies to the unqualified types that are pointed to by the pointers. RationaleCasting a pointer to object into a pointer to a different object may result in a pointer that is not correctly aligned, resulting in undefined behaviour. Even if conversion is known to produce a pointer that is correctly aligned, the behaviour may be undefined if that pointer is used to access an object. For example, if an object whose type is int is accessed as a short the behaviour is undefined even if int and short have the same representation and alignment requirements. See C90 Section 6.3, C99 Section 6.5, paragraph 7 for details. ExceptionIt is permitted to convert a pointer to object type into a pointer to one of the object types char, signed char or unsigned char. The Standard guarantees that pointers to these types can be used to access the individual bytes of an object. Exampleuint8_t *p1; uint32_t *p2; /* Non-compliant - possible incompatible alignment */ p2 = ( uint32_t * ) p1; extern uint32_t read_value ( void ); extern void print ( uint32_t n ); void f ( void ) { uint32_t u = read_value ( ); uint16_t *hi_p = ( uint16_t * ) &u; /* Non-compliant even though * probably correctly aligned */ *hi_p = 0; /* Attempt to clear high 16-bits on big-endian machine */ print ( u ); /* Line above may appear not to have been performed */ } The following example is compliant because the rule applies to the unqualified pointer types. It does not prevent type qualifiers from being added to the object type. const short *p; const volatile short *q; q = ( const volatile short * ) p; /* Compliant */ The following example is non-compliant because the unqualified pointer types are different, namely “pointer to const-qualified int” and “pointer to int”. int * const * pcpi; const int * const * pcpci; pcpci = ( const int * const * ) pcpi; |