Let's say I'm building a byte array to send data over TCP/IP. This byte array contains a string (null terminated char array) along with an integer appended to the end.
So let's do this.
char buffer[24]; // buffer that will be sent over TCP/IP
char hello[7] = "hello"
int x = 12; // int is 4 bytes
So now let's say I perform a memcpy.
memcpy(buffer, hello, 7); // 7 force null character to be copied
memcpy(buffer+7, &x, 4);
By doing this, I believe I'm writing an integer to a non-word-aligned address. I assume this would be a performance hit when packaging the data?
Now let's imagine I send this data out and then receive it on another computer. When I go ahead and unpackage the data, I will need to perform proper casting. However, I'm still attempting to read an integer that isn't word aligned. This will again be a performance hit. I can imagine if I had an array of integers that were all misaligned, this performance hit would add up.
So my question: Is it common practice to word align all integers/floats when sending data over TCP/IP to avoid performance hits? In the case I illustrated above, would it be best to extend the length of the string to size 8 such that the next byte available is word aligned? Does memcpy offer any further methods for automatically compensating for word alignment?
memcpyis the proper thing to do; the compilers optimizememcpyaway when it is safe to do.