在以下示例中:
void bad_function()
{
char_t * ptr = 0;
// MISRA doesn't complains here, it allows cast of char* to void* pointer
void* p2 = ptr;
// the following 2 MISRA violations are reported in each of the casts bellow (two per code line)
// (1) Event misra_violation: [Required] MISRA C++-2008 Rule 5-2-7 violation: An object with pointer type shall not be converted to an unrelated pointer type, either directly or indirectly
// (1) Event misra_violation: [Required] MISRA C++-2008 Rule 5-2-8 violation: An object with integer type or pointer to void type shall not be converted to an object with pointer type
ptr = (char_t*) (p2);
ptr = static_cast<char_t*> (p2);
ptr = reinterpret_cast<char_t*> (p2);
}
报告了 MISRA 5-2-8 和 5-2-7 违规行为。
我怎样才能消除这种违规行为?
我需要有 C++ 静态分析经验的人来帮助我。几天来我对这些愚蠢的规则感到头疼。
根据 MISRA C++ 标准(MISRA-Cpp-2008.pdf:规则 5-2-7(强制):具有指针类型的对象不得直接或间接转换为不相关的指针类型。
好的,但是我们有很多代码,例如需要将地址转换为char*
然后使用它std::ifstream
, which read(char* buffer, int length)
函数需要将地址类型转换为 (char_t*
)。那么,根据 MISRA 人员的说法,如何才能用 C++ 进行编程而不使用任何类型转换呢?标准没有说明必须如何完成指针转换。
在我的生产代码中,我的问题在于使用 read with 进行文件读取操作std::ifstream来自预定义数据结构的文件:
if (file.read((char_t*)&info, (int32_t)sizeof(INFO)).gcount() != (int32_t)sizeof(INFO)
{
LOG("ERROR: Couldn't read the file info header\n");
res = GENERAL_FAILURE;
}
根据 MISRA 应该如何做?
那么有什么解决办法吗?
编辑:Peter 和 Q.Q.答案都是正确的,看来 MISRA 真的想在没有任何演员的情况下完成所有事情,如果项目处于最后阶段,这是很难做到的。有两种选择:
1 - 逐一记录 MISRA 偏差并解释为什么类型转换没问题,解释这是如何测试的(Q.Q.建议)
2 - 使用 char 类型的字节数组进行 file.read(),然后在安全读取文件内容后将字节数组转换为标题内容,必须对每个成员一一执行此操作,因为如果将 char* 转换为 int32_t再次违反规则 5-2-7。有时工作量太大了。