I’m using an open-source networking framework that makes it easy for developers to communicate over a service found using Bonjour in Objective-C.
There are a few lines that have had me on edge for a while now, even though they never seem to have caused any problems on any machines I’ve tested, regardless of whether I’m running the 32-bit of 64-bit version of my application:
int packetLength = [rawPacketData length];
[outgoingBuffer appendBytes:&packetLength length:sizeof(int)];
[outgoingBuffer appendData:rawPacketData];
[self writeToStream];
Note that the first piece of information sent is the length of the data packet, which is pretty standard, and then the data itself is sent. What scares me is the length of the length. Will one machine ever assume an int is 4 bytes, while the other machine believes an int to be 8 bytes?
If the two sizes could be different on different machines, what would cause this? Is it dependent on my compiler, or the end-user’s machine architecture? And finally, if it is a problem, how can I take an 8-byte int and scrunch it down to 4-bytes to ensure backwards compatibility? (Since I’ll never need more than 4 bytes to represent the size of the data packet.)
You can’t assume that
sizeof(int)will always be four bytes. If the size matters, you should either hard-code a size of 4 (and write code to serialize values into four-byte arrays with the proper endianness), or use types likeint32_tdefined in<stdint.h>.(However, as a practical matter, most compiler vendors have decided that
intshould stay four bytes, so you probably don’t need to worry about everything breaking tomorrow. Then again, it wasn’t so long ago that many compiler vendors let anintbe two bytes, leading to many problems whenintsbecame four bytes, so you really ought to do things the right way so guard against future changes.)