PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

aligned network data

Can anyone confirm this?

I am receiving data over the network and cast it to a struct, for example.

Code:
struct packet
{
dword data1;
word data2;
};

void receivedata(byte *networkdata, int size)
{
packet *data = (packet*)networkdata;
data->data1; <-- datatype misalignment
}


My program randomly crashes or generates a datatype misalignment error when doing network operations. I am pretty sure it is because I am accessing a dword when data1 is not dword aligned in memory (because of the cast from networkdata which is a byte*).

So in order to fix this I am going to have to do the following:

Code:
void receivedata(byte *networkdata, int size)
{
packet data;
memcpy(&data, networkdata, sizeof(data));
data.data1; <-- no misalignment anymore because its on the stack
}


I just wanted to double check if anyone else has seen this type of problem before I go and modify all of my receive data code to try to fix this issue.
Yes, everything you wrote is right.

A better fix would be to ensure your byte buffer is int32-aligned, this way your cast would work and you wouldn't need to memcpy() at all.
Yeah that would be better, but I am given a byte* network buffer to get data from (using the enet library) so I can't really control it. I think copying is the only way without modifying the network library to stuff data in when it sees that things need to be aligned.
Then yes. You don't have much of a choice.

You could specify that the structure is unaligned, but it's probably better just to do the memcpy(). Otherwise every access to the structure will be much slower (even more then the memcpy).