主要内容

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

MISRA C:2012 Rule 11.6

A cast shall not be performed between pointer to void and an arithmetic type

描述

规则定义

A cast shall not be performed between pointer to void and an arithmetic type 1 .

理由

整数类型与指向 void 的指针之间的转换可能导致错误或未定义行为。

  • 如果将整数类型强制转换为指针,生成的指针可能存在对齐错误。不正确的对齐会导致未定义的行为。

  • 如果将指针转换为算术类型,则结果值可能会超出该类型的允许范围。

非整数算术类型与指向 void 的指针之间的转换行为未定义。

Polyspace 实现

NULL(void*)0 进行的显式转换或隐式转换不会触发警告。

故障排除

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

示例

全部展开

void foo(void) {

    void          *p;
    unsigned int  u;
    unsigned short r;

    p = (void *) 0x1234u;            /* Non-compliant - undefined */
    u = (unsigned int) p;            /* Non-compliant - undefined */

    p = (void *) 0;                  /* Compliant - Exception */

}

在此示例中,p 是指向 void 的指针。以下情况违反了该规则:

  • 整数值被转换为 p

  • p 被转换为 unsigned int 类型。

如果将值为 0 的整数常量转换为指向 void 的指针,则未违反该规则。

检查信息

组:指针类型转换
类别:必需
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.