Re: alignment problem / gcc compatibility
- From: "John Carson" <jcarson_n_o_sp_am_@xxxxxxxxxxxxxxx>
- Date: Tue, 14 Mar 2006 10:24:11 +1100
"Mycroft Holmes" <m.holmes@xxxxxxxxx> wrote in message
news:%23DwO4ArRGHA.2156@xxxxxxxxxxxxxxxxxxxx
John Carson wrote:
I am not an expert in offsetof (which represents a type of low level
coding that I prefer to avoid), but I don't agree that
offsetof(x, d) >= __alignof(double)
If you use the /Zp4 switch, then offsetof(x, d) equals 4, whereas
__alignof(double) equals 8.
From my understanding, offsetof(x,d) should give you exactly how far
from the start of x the variable d is. Since sizeof(x) must be >=
this value + sizeof(double), the first inequality I gave must be
satisfied and hence the code is legal.
correct, but the point is: by definition, A is the alignment of type T
if it's the smallest positive integer such that EVERY object of type T
must be constructed at an address which is a multiple of A.
"every" includes class data members, so if x::d is a double, I'd
expect it to be aligned as any other double, but if offsetof(x, d) ==
4, then in an array of x of length 2, at least one double will be
misaligned: declare
x a[2];
if a's address is, say, 8N, then a[0].d lies at 8N+4; if a is 8N+4,
then a[1].d lies at (8N+4)+12+4...
The whole point of the packing settings is that you can make types appear at
other than their natural alignment. If you use the /Zp1 switch and declare
struct y
{
double d1;
char c;
double d2;
};
then sizeof(y) is 17 and one double will be at an odd-numbered address.
This is safe but harms performance.
The only time that alignment settings can get you into trouble is when you
use third-party libraries, including Windows dlls. You must #include the
third party header with the same packing values as was used in the
compilation of the third party library, otherwise disaster ensues. In the
case of Windows, #pragmas internal to the header generally ensure this,
though there has been at least one notorious case where the #pragma was
missing. I don't know if the problem has been fixed, but the advice used to
be that if you are using a packing less than 4, then you should use:
#pragma pack(push, 4)
#include <windows.h>
#pragma pack(pop)
--
John Carson
.
- References:
- alignment problem / gcc compatibility
- From: Mycroft Holmes
- Re: alignment problem / gcc compatibility
- From: John Carson
- Re: alignment problem / gcc compatibility
- From: Mycroft Holmes
- Re: alignment problem / gcc compatibility
- From: John Carson
- Re: alignment problem / gcc compatibility
- From: Mycroft Holmes
- alignment problem / gcc compatibility
- Prev by Date: Re: alignment problem / gcc compatibility
- Next by Date: Re: VS2005 standard edition
- Previous by thread: Re: alignment problem / gcc compatibility
- Next by thread: Re: alignment problem / gcc compatibility
- Index(es):
Relevant Pages
|