On Github chihungtzeng / struct_pack
int main(int argc, char *argv[]){
struct {
char c; // 1 byte, followed by 7-byte padding
long long ell; // 8 bytes
short s; // 2 bytes, followed by 6-byte padding
} s;
printf("sizeof(s) is %lu\n", sizeof(s)); // sizeof(s) is 24
return 0;
}
int main(int argc, char *argv[]){
struct {
long long ell; // 8 bytes
short s; // 2 bytes
char c; // 1 byte, followed by 5-byte padding
} s;
printf("sizeof(s) is %lu\n", sizeof(s)); // sizeof(s) is 16
return 0;
}
24 bytes 變成 16 bytes, 33% improvement!
int main(int argc, char *argv[]){
struct {
char c; // 1 byte, followed by 7-byte padding
long long ell; // 8 bytes
short s; // 2 bytes, followed by 6-byte padding
} s;
printf("sizeof(s) is %lu\n", sizeof(s)); // sizeof(s) is 24
return 0;
}
$ gcc -Wpadded bad_struct.c
ad_struct.c: In function ‘main’: bad_struct.c:6:19: warning: padding struct to align ‘ell’ [-Wpadded] bad_struct.c:8:5: warning: padding struct size to alignment boundary [-Wpadded]
$ clang -Wpadded bad_struct.c
bad_struct.c:6:19: warning: padding struct 'struct <anonymous at
bad_struct.c:4:5>' with 7 bytes to align 'ell' [-Wpadded]
long long ell;
^
bad_struct.c:4:5: warning: padding size of 'struct <anonymous at
bad_struct.c:4:5>' with 6 bytes to alignment boundary [-Wpadded]
struct {
^
2 warnings generated.
clang has more detailed output than gcc