Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen is char* safe for strict pointer aliasing?
    primarykey
    data
    text
    <p>I've been trying to understand the strict aliasing rules as they apply to the char pointer.</p> <p><a href="http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html#cast_to_char_pointer" rel="nofollow noreferrer">Here</a> this is stated:</p> <blockquote> <p>It is always presumed that a char* may refer to an alias of any object.</p> </blockquote> <p>Ok so in the context of socket code, I can do this:</p> <pre><code>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*)(&amp;msgToSend), sizeof(msgToSend); }; </code></pre> <p>But then there's this statement</p> <blockquote> <p>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. </p> </blockquote> <p>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:</p> <pre><code>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 = &amp;msgBuff[0]; printf("Got Msg: a: %i, b: %i", pointerToMsg-&gt;a, pointerToMsg-&gt;b); } </code></pre> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload