Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizes of structs on 32 bit and 64 bit

In the .NET struct design guidelines, it gives the maximum sensible size of a struct as 16 bytes. How do you determine how large your struct is, and is it affected by the architecture your program is running on? Is this value 32-bit only, or for both archs?

like image 909
thecoop Avatar asked Jul 27 '09 16:07

thecoop


People also ask

What is the sizeof this struct in 32-bit and 64-bit machines?

In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes. Structure padding is used to save number of CPU cycles.

What will be the size of the struct for a 64-bit machine?

In the 64-bit build mode the structure MyStruct will take 24 bytes. It is clear. First there is one byte for m_bool and 7 vacant bytes for the purpose of alignment because a pointer takes 8 bytes and must be aligned on an 8-byte boundary.

What is the size of structure in 32bit operating system?

One bit in the register can reference an individual byte in memory, so a 32-bit system can address a maximum of 4 GB (4,294,967,296 bytes) of RAM. The actual limit is often less than around 3.5 GB since part of the register is used to store other temporary values besides memory addresses.

What is the size of the C structure below on a 32-bit system on a 64-bit?

Therefore, we can say that a 32-bit processor is capable of accessing 4 bytes at a time, whereas a 64-bit processor is capable of accessing 8 bytes at a time.


1 Answers

It's not a hard-and-fast value - it's just a guideline, a rule of thumb. Depending on the exact situation, 24 or even 32 bytes could still be perfectly justifiable - but if your struct gets that large you should really be asking yourself whether it's appropriate as a struct in the first place. It may be - in which case taking the hit of copying those 32 bytes around any time you perform an assignment or pass an argument into a method (etc) may be the right thing to do; in other cases you should really be using a class.

As for how you determine how big your struct is - usually it's fairly obvious, because usually a value type only contains other value types. If your struct contains references (or an IntPtr/UIntPtr), that's more of a problem - but that's pretty rare. (As Mehrdad points out, there's also the issue of padding for the sake of alignment.)

Then again, I find it extremely rare that I want to write my own struct anyway. What's your situation?

like image 112
Jon Skeet Avatar answered Sep 23 '22 15:09

Jon Skeet