0

I have a compiler warning ('type dereferencing type-punned pointer will break strict-aliasing rule') in this code:

volatile uint8_t Buff[READ_BUFF_SIZE];

#define   LD_DWORD(ptr)      (DWORD)(*(DWORD*)(BYTE*)(ptr))

ChunkID = LD_DWORD(&Buff[0]); <-- here is warning

I am on 32 bit Cortex M0.

Despite the warning, it is working fine. My question is, can the warning be solved?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user1797147
  • 915
  • 3
  • 14
  • 33

1 Answers1

3

Reinterpreting objects that don't have allocated storage duration as objects of some other (incompatible) type is undefined behavior.

In your example Buffwhich has type uint8_t which has either static or automatic storage duration, is being reinterpreted as type DWORD. Those type are not compatible1, the behavior is not defined.

You should simply define Buff as type you intend to use, which appears to be DWORD:

volatile DWORD Buff[READ_BUFF_SIZE];

and then you don't need macros for access, simply using the built-in operator will do:

ChunkID = Buff[0];

1 Even if we assume2 uint8_t is defined as unsigned char, which may alias any type, the type DWORD may not alias unsigned char.

2 Standard permits that the type uint8_t is not defined as unsigned char even if CHAR_BIT is 8. See extended integer types.

2501
  • 25,460
  • 4
  • 47
  • 87
  • Yeah, it's a decent answer — but it doesn't make the question less of a duplicate. – Jonathan Leffler Jul 19 '16 at 19:26
  • @JonathanLeffler Only 'decent'? :-) Yeah I guess it's 'kinda' a dup. – 2501 Jul 19 '16 at 19:34
  • Ok, got'it and make sense! I always want to know why are warnings generated. Thanks for links, I read some and understood. I cannot declare my buffer as other than uint8 since there are many routines that use it as is. But in several others, data makes sense as uint16, uint32 etc. I solve it more ellegant by using unions on original buffer. Thanks. – user1797147 Jul 20 '16 at 16:59
  • @user1797147 You could use malloc. Allocated memory is more flexible. – 2501 Jul 20 '16 at 17:02