主要内容

MISRA C:2012 Rule 11.4

A conversion should not be performed between a pointer to object and an integer type

描述

规则定义

A conversion should not be performed between a pointer to object and an integer type 1 .

理由

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

  • 如果将整数转换为指针,得到的指针可能会没有正确对齐。对齐不正确会导致未定义行为。

  • 如果将指针转换为整数,得到的值可能会超出整数类型的允许范围。

Polyspace 实现

NULL(void*)0 进行转换或隐式转换不会生成警告。

故障排除

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

示例

全部展开

#include <stdbool.h>

typedef unsigned char      uint8_t;
typedef          char      char_t;
typedef unsigned short     uint16_t;
typedef signed   int       int32_t;

typedef _Bool bool_t;
uint8_t *PORTA = (uint8_t *) 0x0002;            /* Non-compliant */

void foo(void) {

    char_t c = 1;
    char_t *pc = &c;                              /* Compliant */


    uint16_t ui16   = 7U;
    uint16_t *pui16 = &ui16;                      /* Compliant */
    pui16 = (uint16_t *) ui16;                    /* Non-compliant */


    uint16_t *p;
    int32_t addr = (int32_t) p;                  /* Non-compliant */
    bool_t b = (bool_t) p;                       /* Non-compliant */
    enum etag { A, B } e = ( enum etag ) p;      /* Non-compliant */
}

在此示例中,当出现以下情况时便会违反规则:

  • 整数 0x0002 被转换为指针。

    如果整数定义了一个绝对地址,通常会在头文件中将该地址赋值给一个指针。为了避免该赋值被标记出来,您可以将头文件排除在编码规则检查之外。有关详细信息,请参阅不为以下项生成结果 (-do-not-generate-results-for)

  • 指针 p 被转换为整数类型,例如 int32_tbool_tenum etag

当地址 &ui16 被赋值给指针时,不违反该规则。

检查信息

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