CPPCheck在输出中打印无效字符

时间:2018-04-23 07:09:21

标签: c++ cppcheck

我在以下代码

上运行cppcheck
bool  bsIsBigEndian( void )
{
    return (((const int*)"\0\x1\x2\x3\x4\x5\x6\x7")[0] & 255) != 0;
}

使用以下命令

cppcheck --template={file};{line};{severity};{message};{id} --enable=style,performance,portability file.cpp

输出

打印 enter image description here

我尝试过--platform选项,但结果仍然相同。 如何摆脱无效字符?

1 个答案:

答案 0 :(得分:1)

您的代码有undefined behaviour

您正在向const char *转换const int *,这可能(并且因为它是一个字符串常量而且编译器可能不会对齐它)会有不同的对齐方式。您的代码可以这样修复。

bool bsIsBigEndian() {
    const char *text = "\0\x1\x2\x3\x4\x5\x6\x7";
    int value;
    std::memcpy(&value, text, sizeof value);
    return (value & 255) != 0;
}

memcpy忽略对齐问题,这是正确的,因为int长8个字节长或更短,在大多数平台上长4个字节。

也可以通过编写const char text[] = {0, 1, 2, 3, 4, 5, 6, 7};来消除字符串常量。