Main Content

MISRA C:2023 Rule 11.8

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

Since R2024a

Description

Rule Definition

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

Rationale

This rule forbids conversions that violate type qualification:

  • Casts from a pointer to a const object to a pointer that does not point to a const object. Removing the const qualifier allows the program to modify objects that are intended to be read-only. Attempting to access such a converted object can result in an exception.

  • Casts from a pointer to a volatile object to a pointer that does not point to a volatile object. Removing the volatile qualifier can allow the compiler to remove accesses to this object during optimization.

  • Casts from a pointer to an _Atomic object to a pointer that does not point to a _Atomic object. Removing the _Atomic qualifier allows the program to circumvent the lock status of an object, resulting in memory corruption.

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 Diagnose Why Coding Standard Violations Do Not Appear as Expected.

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 pi = cpi;. The assignment does not remove the const nature of the object pointed to by cpi. While cpi is const object, it points to a nonconst object. Polyspace does not report a violation in such cases.

Check Information

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

Version History

Introduced in R2024a