主要内容

MISRA C:2023 Rule 8.13

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

自 R2024a 起

描述

规则定义

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 类别:建议

版本历史记录

在 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.