Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is sizeof(int) not 4 bytes in Objective-C?

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.)

like image 399
Craig Otis Avatar asked Mar 07 '11 14:03

Craig Otis


People also ask

Is sizeof int always 4?

Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.

Are integers in C always 4 bytes?

For example, an int is defined by the C standard to be at least 16 bits. a 32-bit CPU might process 32-bit numbers efficiently, and so an int might be stored in 32 bits (or 4 bytes) for that CPU.

How many bytes is an int in C?

The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -2147483648 to 2147483647 .


2 Answers

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 like int32_t defined in <stdint.h>.

(However, as a practical matter, most compiler vendors have decided that int should 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 an int be two bytes, leading to many problems when ints became four bytes, so you really ought to do things the right way so guard against future changes.)

like image 139
Kristopher Johnson Avatar answered Sep 22 '22 14:09

Kristopher Johnson


It could be different, but this depends on the compiler more than the machine. A different compiler might redeclare int to be 8 bytes.

like image 44
GolezTrol Avatar answered Sep 20 '22 14:09

GolezTrol