MISRA C:2012 Rule 11.8

A cast shall not remove any const or volatile qualification from the type pointed to by a pointer

Description

Rule Definition

A cast shall not remove any const or volatile qualification from the type pointed to by a pointer.

Rationale

This rule forbids:

  • Casts from a pointer to a const object to a pointer that does not point to a const object.

  • Casts from a pointer to a volatile object to a pointer that does not point to a volatile object.

Such casts violate type qualification. For example, the const qualifier indicates the read-only status of an object. If a cast removes the qualifier, the object is no longer read-only.

Polyspace Implementation

Polyspace® flags both implicit and explicit conversions that violate this rule.

Troubleshooting

If you expect a rule violation but do not see it, refer to the documentation of Polyspace Code Prover™ or Polyspace Code Prover Server™.

Examples

expand all

void foo(void) {

    /* Cast on simple type */
    unsigned short           x;
    unsigned short * const   cpi = &x;  /* const pointer */
    unsigned short * const  *pcpi;   /* pointer to const pointer */
    unsigned short **ppi;
    const unsigned short    *pci;    /* pointer to const */
    volatile unsigned short *pvi;    /* pointer to volatile  */
    unsigned short          *pi;

    pi = cpi;                        /* Compliant - no cast required */
    pi  = (unsigned short *)  pci;   /* Non-compliant */
    pi  = (unsigned short *)  pvi;   /* Non-compliant */
    ppi = (unsigned short **)pcpi;   /* Non-compliant */
}

In this example:

  • The variables pci and pcpi have the const qualifier in their type. The rule is violated when the variables are cast to types that do not have the const qualifier.

  • The variable pvi has a volatile qualifier in its type. The rule is violated when the variable is cast to a type that does not have the volatile qualifier.

Even though cpi has a const qualifier in its type, the rule is not violated in the statement p=cpi;. The assignment does not cause a type conversion because both p and cpi have type unsigned short.

Check Information

Group: Pointer Type Conversions
Category: Required
AGC Category: Required
Introduced in R2014b