I want to rewrite a piece of (old) code to be standards compliant. The old code uses a buffer to store a POD-struct and a checksum to send it over the network and receive it. For sending, the code looks like:
struct MessageStruct {int a; float b;};
char buffer[sizeof(MessageStruct) + sizeof(uint32_t)];
((MessageStruct*)buffer)->a = 12;
((MessageStruct*)buffer)->b = 3.14159f;
*((uint32_t*)(buffer + sizeof(MessageStruct))) = 9876;
// Use the data buffer in some way.
SendMessage(buffer, sizeof(buffer));
For receiving, the code looks like:
struct MessageStruct {int a; float b;};
// Receive: char *buffer, int size
const MessageStruct *message = (MessageStruct*)buffer;
uint32_t checksum = *((uint32_t*)(buffer + sizeof(MessageStruct)));
How do I update this code to make it fully standards complaint, in particular not in violation of the strict aliasing rule?
I've found posts addressing similar issues: strict aliasing and alignment , Shared memory buffers in C++ without violating strict aliasing rules . However, none of these really answer my question; or maybe they do, but then I don't see it.
Update: As some of the answers have already stated, the easiest way is to use memcpy
. I am wondering, is there any way to do this using placement new, or another construct that negates the need for copying and constructs it in-place?