主要内容

MISRA C:2023 Rule 11.6

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

自 R2024a 起

描述

规则定义

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 类别:必需

版本历史记录

在 R2024a 中推出


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.