主要内容

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

MISRA C:2012 Dir 4.8

If a pointer to a structure or union is never dereferenced within a translation unit, then the implementation of the object should be hidden

描述

规则定义

If a pointer to a structure or union is never dereferenced within a translation unit, then the implementation of the object should be hidden 1 .

理由

如果在文件中未对指向结构体或联合体的指针进行解引用,则该结构体或联合体的实现细节无需在该文件的翻译单元中提供。您可以隐藏实现细节(如结构体成员)并防止它们被意外修改。

定义一种不透明类型,该类型可以通过指针进行引用,但其内容无法被访问。

Polyspace 实现

如果结构或联合在文件或文件中包含的头文件中定义,则声明了指向该结构或联合的指针,但该指针在文件中从未被解引用,检查项会标记为编码违规。该结构或联合体定义不应在此文件中可见。

如果在结构体定义中发现违反此规则的情况,请确认是否在同一文件中或在该文件包含的头文件中定义了指向该结构体的指针。然后检查文件中是否在任何位置对该指针进行了解引用。如果未对指针进行解引用,则该结构体的定义应从本文件及包含的头文件中隐藏。

结构的大小可以在运行时发生变化。如果在翻译单元中使用 sizeof() 运算符计算结构的大小,Polyspace® 假设该结构的实现必须在翻译单元中提供。如果翻译单元中存在此结构,则 Polyspace 不会报告违规。

故障排除

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

示例

全部展开

file.h:包含结构实现。


#ifndef TYPE_GUARD
#define TYPE_GUARD

typedef struct  {  //Noncompliant
  int a; 
} myStruct; 

#endif

file.c:包括 file.h,但不解引用结构。


#include "file.h"

myStruct* getObj(void);
void useObj(myStruct*);

void func() {
  myStruct *sPtr = getObj();
  useObj(sPtr);
}

在此示例中,对类型 myStruct 的指针未被解引用。指针直接从 getObj 函数中获得,然后传递给 useObj 函数。

myStruct 的实现可以在由 file.cfile.h 组成的翻译单元中看到。

更正 - 定义不透明类型

一种可能的更正是,在头文件 file.h 中定义一个不透明的数据类型。不透明数据类型 ptrMyStruct 指向 myStruct 结构体,但不透露该结构体包含的内容。结构体 myStruct 本身可以定义在单独的翻译单元中,在本例中,该翻译单元由文件 file2.c 组成。通用头文件 file.h 必须同时包含在 file.cfile2.c 中,以便将结构体定义与不透明类型定义进行链接。

file.h:不包含结构实现。


#ifndef TYPE_GUARD
#define TYPE_GUARD

typedef struct myStruct *ptrMyStruct; 

ptrMyStruct getObj(void);
void useObj(ptrMyStruct);

#endif

file.c:包括 file.h,但不解引用结构。


#include "file.h"

void func() {
  ptrMyStruct sPtr = getObj();
  useObj(sPtr);
}

file2.c:包括 file.h 及解引用结构。


#include "file.h"

struct myStruct {                                               
  int a;                                                    
};

void useObj(ptrMyStruct ptr) {
    (ptr->a)++;
}

检查信息

组:代码设计
类别:建议
AGC 类别:建议

版本历史记录

在 R2018a 中推出


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.