Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the structure size differ in 32-bit and 64-bit program?

Tags:

c++

c

The following is a simple C program:

#include <stdio.h>

typedef struct
{
    char a;
    double b;
} A;
int main(void) {
    printf("sizeof(A) is %d bytes\n", sizeof(A));
    return 0;
}

When I compiled it into 32-bit program, the output is:

sizeof(A) is 12 bytes

I know the structure memory modle should be:

 ____________________________
|a|3 padding| b              |
 ————————————————————————————

But When I compiled it into 64-bit program, the output is:

sizeof(A) is 16 bytes

So the structure memory modle should be:

 ____________________________________
|a|7 padding        | b              |
 ____________________________________

Personally, I think no matter the program is 32-bit or 64-bit, the size of structure should always be 16 bytes (since char is 1 byte long, and the alignment of double is 8 bytes). Why the size is 12 bytes in 32-bit program?

like image 253
Nan Xiao Avatar asked May 26 '26 06:05

Nan Xiao


1 Answers

On Intel CPU, BOTH 32-bit and 64-bit machine, floating-point instruction of the "SIMD" variation read/write either 16 bytes ( 2 doubles) or 8 bytes (a single double), at a single machine instruction. Those are the most common instructions for handling floating-points. It is all a matter of SPEED:

Reading a single data item may be done either by "the aligned read instruction", or by the "unaligned read instruction". The aligned version is ensured to be quicker. Unaligned instruction has to deal with complicated cases where the data is split between two cache lines, or even two different memory pages. Further more, the CPU is optimized for certain instructions, namely the aligned ones. So much optimized, that reading a 1-byte data is more time-consuming then reading 16 aligned bytes. The archaic 1-bytes instructions of the 8088 ( MOV AL / MOV AH etc) are not hardware optimized.

The Compiler writer has to choose either a dense code, or a fast code. In the old days when my PC had 16 KB of memory, memory was scarce. Later, one could instruct the compiler exactly how to align structure members. When 64-bits CPU came out, memory was cheap enough that structures sizes became a multiple of 16-bytes, and each structure member is aligned on its natural boundary - according to its type: even address for shorts, mod(4,0) for int and floats, mod(8,0) for _int64 and doubles, mod(16,0) for _mm128, mode(32,0) for _mm256

like image 103
zalia64 Avatar answered May 30 '26 07:05

zalia64



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!