I know there is padding in struct (example from this post)
struct A -->8 bytes
{
char c;
char d;
//2 padding here
int i;
};
struct B -->12 bytes
{
char c;
//3 padding here
int i;
char d;
//3 padding here
};
Now, I don't understand following example:
typedef struct { -->**shouldn't it be 12 bytes**
int a;
char *str;
} TestS;
TestS s;
int main(int argc, char *argv[]) {
printf("An int is %lu bytes\n", sizeof( int )); -->4
printf("A Char * is %lu bytes\n", sizeof( char *)); -->8
printf("A double is %lu bytes\n", sizeof( double )); -->8
printf("A struct is %lu bytes\n", sizeof s); -->why 16?
return 0;
}
First I thought it may aligning to 8*N byte (for I use ubuntu-64), so I try more structs.
typedef struct {
int i;
char *str;
} stru_12;
typedef struct {
int i;
char *str;
char c;
} stru_13;
typedef struct {
int i;
char str[7];
} stru_11;
typedef struct {
char *str;
double d;
} stru_16;
stru_12 test12;
stru_13 test13;
stru_11 test11;
stru_16 test16;
int main (int argc, char *argv[]) {
printf("A test12 is %lu bytes, address is %p\n", sizeof test12, &test12);
printf("A test13 is %lu bytes, address is %p\n", sizeof test13, &test13);
printf("A test11 is %lu bytes, address is %p\n", sizeof test11, &test11);
printf("A test16 is %lu bytes, address is %p\n", sizeof test16, &test16);
}
Result:
A test12 is 16 bytes, address is 0x601060
A test13 is 24 bytes, address is 0x601090
A test11 is 12 bytes, address is 0x601080
A test16 is 16 bytes, address is 0x601070
Sorry for being so long.
My question is:
Why test12 (int + char*) is 16 bytes and test13 (int + char * + char) is 24?(it seems that 8*N is favored, but 12 bytes is allowed )
Why the differences of the addresses of structs is 16 addressing unit (more padding?)?
For your use:
cache_alignment : 64
address sizes : 36 bits physical, 48 bits virtual
Ubuntu 14.04.1 LTS x86_64