1

I have a third-party piece of code to compile, below is the snippet that fails:

typedef struct wqe_s {
   ...
   uint8_t packet_data[96]
   ...
} wqe_t;

..
wqe_t *work = NULL;
..
wqe_t *w1 = *(wqe_t **)work->packet_data;  // ERROR

error: dereferencing type-punned pointer will break strict-aliasing rules

It is compiled with gcc-4.7 (-Wall -Werror), I don't think I need to adjust compiler flags, the best would be to fix the code.

I would appreciate to get some advice for this. Thanks!

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Mark
  • 6,052
  • 8
  • 61
  • 129
  • This code and the right solution below still have the portability problem of endianness. May be in the real program it is taken care of but this excerpt does not. – Patrick Schlüter Mar 19 '15 at 10:26

1 Answers1

3

Like this:

wqe_t *w1;
memcpy(&w1, work->packet_data, sizeof w1);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • @Kerrek DB, thanks for response. I'm not sure I'm following your suggestion -- you copy [sizeof w1] bytes of memory from area pointed by work->packet_data to where pointer w1 is located, i.e. on the stack, however in the original code (which gcc isn't happy about) they copy pointers. Correct me if I'm wrong. – Mark Mar 17 '15 at 19:14
  • @Mark: The original code pretends that an area of memory is an object of a certain type `T` (which is the illegal type punning) by treating the pointer to the memory as a pointer-to-`T` and dereferencing that. My code creates an actual object of type `T` (so there is now such an object) and then copies data into its underlying representation. (Here `T = wqe_t*`.) – Kerrek SB Mar 17 '15 at 19:22