I've been trying to understand the strict aliasing rules as they apply to the char pointer.
Here this is stated:
It is always presumed that a char* may refer to an alias of any object.
Ok so in the context of socket code, I can do this:
struct SocketMsg
{
int a;
int b;
};
int main(int argc, char** argv)
{
// Some code...
SocketMsg msgToSend;
msgToSend.a = 0;
msgToSend.b = 1;
send(socket, (char*)(&msgToSend), sizeof(msgToSend);
};
But then there's this statement
The converse is not true. Casting a char* to a pointer of any type other than a char* and dereferencing it is usually in violation of the strict aliasing rule.
Does this mean that when I recv a char array, I can't reinterpret cast to a struct when I know the structure of the message:
struct SocketMsgToRecv
{
int a;
int b;
};
int main()
{
SocketMsgToRecv* pointerToMsg;
char msgBuff[100];
...
recv(socket, msgBuff, 100);
// Ommiting make sure we have a complete message from the stream
// but lets assume msgBuff[0] has a complete msg, and lets interpret the msg
// SAFE!?!?!?
pointerToMsg = &msgBuff[0];
printf("Got Msg: a: %i, b: %i", pointerToMsg->a, pointerToMsg->b);
}
Will this second example not work because the base type is a char array and I'm casting it to a struct? How do you handle this situation in a strictly aliased world?