主要内容

MISRA C:2012 Rule 11.3

A conversion shall not be performed between a pointer to object type and a pointer to a different object type

描述

A conversion shall not be performed between a pointer to object type and a pointer to a different object type 1 .

理由

如果将指向某个对象的指针转换为指向其他对象的指针,得到的指针可能不会正确对齐。对齐不正确会导致未定义行为。

即使转换后生成的指针是正确对齐的,如果使用该指针访问对象,其行为仍可能未定义。

作为例外,MISRA C:2012 标准允许将指向非 atomic 限定对象类型的指针转换为指向以下类型之一的指针:

  • char

  • signed char

  • unsigned char

故障排除

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

示例

全部展开

signed   char *p1;
unsigned int *p2;

void foo(void){ 
  p2 = ( unsigned int * ) p1;     /* Non-compliant */				
}

在此示例中,p1 可以指向 signed char 对象。但是,p1 转换为指向更宽类型对象(即 unsigned int)的指针。

extern unsigned int read_value ( void );
extern void display ( unsigned int n );

void foo ( void ){
  unsigned int u = read_value ( );
  unsigned short *hi_p = ( unsigned short * ) &u;    /* Non-compliant  */	
  *hi_p = 0;                                         
  display ( u );                                     
}

在此示例中,u 是一个 unsigned int 变量。&u 转换为指向更窄类型对象(即 unsigned short)的指针。

在 big-endian 计算机上,*hi_p = 0 语句尝试清除 &u 所指向的内存位置的高位。但是,从 display(u) 的结果来看,您可能会发现高位没有被清除。

typedef struct {
	int iNum1;
}A;

typedef struct {
	int iNum2;
}B;

void bar(A*);

void foo() {
	B wrappedNum2;
	bar(&wrappedNum2); /* Noncompliant*/

}

在此示例中,在调用 bar 时,B 类型的 struct 对象 wrappedNum2 隐式转换为 A 类型的 struct 对象。Polyspace® 标记出了该隐式转换。

const short *p;
const volatile short *q;
void foo (void){
  q = ( const volatile short * ) p;  /* Compliant */								
}

在此示例中,pq 都指向 short 对象。它们之间的转换只添加了一个 volatile 限定符,因此是合规的。

检查信息

组:指针类型转换
类别:必需
AGC 类别:必需
PQL 名称:std.misra_c_2012.R11_3

版本历史记录

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