主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 11.8

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

描述

规则定义

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

理由

此规则禁止违反类型修饰符的转换:

  • 将指向 const 对象的指针转换为不指向 const 对象的指针。删除 const 修饰符后,程序可以修改原本为只读的对象。尝试访问此类转换后的对象可能会导致异常。

  • 将指向 volatile 对象的指针转换为不指向 volatile 对象的指针。删除 volatile 修饰符可以允许编译器在优化期间删除对该对象的访问。

  • 将指向 _Atomic 对象的指针转换为不指向 _Atomic 对象的指针。删除 _Atomic 修饰符后,程序可以绕过对象的锁状态,导致内存损坏。

此类转换违反类型限定。例如,const 修饰符表示对象的只读状态。如果转换删除了限定符,则对象不再为只读。

Polyspace 实现

Polyspace® 标记违反此规则的隐式和显式转换。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

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 */
}

在此示例中:

  • 变量 pcipcpi 的类型中包含 const 限定符。当变量被转换为不具有 const 修饰符的类型时,该规则被违反。

  • 变量 pvi 的类型中包含 volatile 限定符。当变量被转换为不具有 volatile 修饰符的类型时,该规则被违反。

尽管 cpi 的类型中包含 const 限定符,但在语句 pi = cpi; 中并未违反该规则。该赋值不会删除 const 所指向对象的 cpi 性质。虽然 cpiconst 对象,但它指向了一个非 const 对象。在这种情况下,Polyspace 不会报告违规。

检查信息

组:指针类型转换
类别:必需
AGC 类别:必需

版本历史记录

在 R2014b 中推出

全部展开


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.