これはメモリアラインメントに関するものです。以下のコードでは、構造内の b のオフセットが 8 (32 ビット マシン) であると予想しました。ここを参照してください。これにより、b
常にキャッシュ ライン内で発生するようになります。しかし、そうではありません。b
のグローバル オブジェクトのメンバーはstruct test1
整列しているようです。偶然なのか、コンパイラが意図的にこれを行っているのかはわかりません。
コンパイラが の後に 4 バイトをパディングしない理由を理解したかったの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;
}
出力は...
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
ubuntu 10.04で標準のgccコンパイラを使用しています