2

I have this warning on my cast line code:

dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict- aliasing]

unsigned char buffer[64];
...
unsigned int value = *(unsigned int*)buffer;

How to fix this warning ?

Thanks for your help !

anthony
  • 7,653
  • 8
  • 49
  • 101
  • 2
    Do you understand what the warning is telling you? You will need to understand the problem before you can actually fix it. There are many ways to silence the warning *without* fixing the real problem, and merely silencing the warning would be completely pointless. –  Dec 24 '14 at 09:29
  • 3
    the duplicate is a C question, this is a C++ question. This is important because one of the suggested fixes on the "duplicate" is to use a `union` which does not work in C++. – M.M Dec 24 '14 at 09:44
  • @MattMcNabb Good point. In fact, none of the answers there are useful as an answer here. I've re-opening this one for that reason. –  Dec 24 '14 at 10:25
  • Ah yes, type-punning. Not the language's nor gcc's finest hour. [Here's](http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html) an excellent write up that goes through all the if's, but's and maybe's associated with what you're trying to do. Good luck! – Andy Brown Dec 24 '14 at 10:48
  • Without knowing what the code is supposed to do, it's hard to help you. The code's behavior will be platform specific, and without knowing your platform, there's no way for us to know what it was supposed to do. There are ways to do whatever it was doing, but we don't know what that is. – David Schwartz Dec 24 '14 at 10:51

2 Answers2

4

What this code does depends on the platform's endianness, alignment rules, integer size, and other things. There's no way to know what it does just by looking at it. But you probably want something like this:

unsigned int value = buffer[0];
value = (value << 8) | buffer[1];
value = (value << 8) | buffer[2];
value = (value << 8) | buffer[3];
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
2

How to fix this warning ?

By not using type-punning to begin with. In this example, you can use memcpy() instead;

unsigned char buffer[64];
...
unsigned int value;
memcpy(&value, buffer, sizeof(value));

If endian is an issue, you can swap the bytes of value afterwards. Or, you can use a bit-shifting solution, like @DavidSchwartz's answer shows.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770