主要内容

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

MISRA C:2012 Rule 8.13

A pointer should point to a const-qualified type whenever possible

描述

规则定义

A pointer should point to a const-qualified type whenever possible 1 .

理由

此规则可确保您不会无意中使用指针来修改对象。

Polyspace 实现

如果指针未修改所引用的对象,规则检查项会标记指向非 const 函数参数的指针。假设指针并非用于修改对象,因此必须指向 const- 合格类型。如果非 const 指针所指向的数据被指针的副本修改,则 Polyspace® 不会设置标记。

故障排除

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

示例

全部展开

#include <string.h>

typedef unsigned short uint16_t;

uint16_t ptr_ex(uint16_t *p) {      /* Non-compliant */
    return *p;
}

char last_char(char * const s){     /* Non-compliant */
    return s[strlen(s) - 1u];
}

uint16_t first(uint16_t a[5]){      /* Non-compliant */
    return a[0];
}

此示例显示了三个不同的不合规的指针参数。

  • ptr_ex 函数中,p 不修改对象。然而,p 所指向的类型并非 const 限定类型,因此不合规。

  • last_char 中,指针 s 是常量,但它所指向的类型不是 const 限定类型。此参数不合规,因为 s 不会修改对象。

  • 函数 first 不修改数组 a 的元素。然而,元素类型未经过 const 限定,因此 a 也不合规。

更正 - 使用 const 关键字

一种可能的更正是为定义添加 const 修饰符。

#include <string.h>

typedef unsigned short uint16_t;

uint16_t ptr_ex(const uint16_t *p){     /* Compliant */
    return *p;
}

char last_char(const char * const s){   /* Compliant */
    return s[strlen( s ) - 1u];
}

uint16_t first(const uint16_t a[5]) {   /* Compliant */
    return a[0];
}

检查信息

组:声明和定义
类别:建议
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.