1

I am running cppcheck on the following piece of code

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

with the command below

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

Output

Prints in enter image description here

I have tried --platform option but still same result. How can I get rid of invalid characters ?

pranay jain
  • 352
  • 1
  • 2
  • 15
  • 1
    cppcheck is an old tool, and it fails on lots of things - just skip those errors or warnings – BЈовић Apr 23 '18 at 07:14
  • I do not understand what sort of output you are getting from cppcheck. You should get a well defined output, with statistics relating to the check. Can you post the full output please? – Rann Lifshitz Apr 23 '18 at 07:15
  • 1
    Seems to be `[test.cpp:3]: (style) Condition '(((const int*)"")[0]&255)!=0' is always false`. Seems like a cppcheck bug, but one that doesn't make the error message unusable. I mean, it printed unprintable characters, but that's non-important as it also provides context like a line number. – Konrad Borowski Apr 23 '18 at 07:34
  • @RannLifshitz: Added output image – pranay jain Apr 23 '18 at 07:37
  • @xfix: You are right about the trivial nature of message as we have the line number already, but I use the error message further in my code and it gives me error due to invalid characters. – pranay jain Apr 23 '18 at 07:41
  • Can't you just use valid characters in the code? (`"\01234567"` would be just as useful for this test). – Toby Speight Apr 23 '18 at 14:09

1 Answers1

1

Your code has undefined behaviour.

You are casting a const char * to const int * which may (and will, because it's a string constant and the compiler likely won't bother aligning it) have different alignment. Your code can be fixed as such.

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 ignores alignment issues, and this is correct as long int is 8 bytes long or smaller, on most platforms it is 4 bytes long.

Also it's possible to get rid of a string constant by writing const char text[] = {0, 1, 2, 3, 4, 5, 6, 7}; instead.

Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71
  • I have problem running cppcheck on the above piece of code. So the code may be incorrect. I am more worried about the output of cppcheck – pranay jain Apr 23 '18 at 07:31
  • @pranayjain I mean, this is a bug in cppcheck. [Report the issue to its developer.](https://trac.cppcheck.net/) – Konrad Borowski Apr 23 '18 at 07:32