This is about memory alignment. In the code below, I expected the offset b inside the structure to be 8 (32-bit machine). See here . There, when b always occurs in the cache line. However, it is not. The b element in the global struct test1 object seems aligned. I am not sure if this is accidental or the compiler does it intentionally.
I wanted to understand why the compiler does not fill 4 bytes after a .
struct test1 { int a; double b; }t1; int main() { struct test1 *p = malloc(sizeof(struct test1)); printf("sizes int %d, float %d, double %d, long double %d\n", sizeof(int), sizeof(float), sizeof(double), sizeof(long double)); printf("offset of b %d\n",(int)&(t1.b)-(int)&(t1)); printf("\naddress of b (on heap) = %p, addr of b (on data seg) = %p\n",&(p->b), &(t1.b)); return 0; }
Output...
sizes int 4, float 4, double 8, long double 12 offset of b 4 address of b (on heap) = 0x804a07c, addr of b (on data seg) = 0x80497e0
I am using the standard gcc compiler on ubuntu 10.04
source share